jboss enterprise application platform 4.3 seam 2 · pdf filethe jsf configuration: ... 1.6.5....

387
JBoss Enterprise Application Platform 4.3 Seam 2 Reference Guide for Use with JBoss Enterprise Application Platform 4.3.0 Edition 4.3.10 Last Updated: 2017-10-13

Upload: dinhnhan

Post on 09-Mar-2018

233 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

JBoss Enterprise Application Platform4.3

Seam 2 Reference Guide

for Use with JBoss Enterprise Application Platform 4.3.0

Edition 4.3.10

Last Updated: 2017-10-13

Page 2: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference
Page 3: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

JBoss Enterprise Application Platform 4.3 Seam 2 Reference Guide

for Use with JBoss Enterprise Application Platform 4.3.0Edition 4.3.10

Gavin King

Pete Muir

Norman Richards

Shane Bryzak

Michael Yuan

Mike Youngstrom

Christian Bauer

Jay Balunas

Dan Allen

Max Andersen

Emmanuel Bernard

Edited by

Samson Kittoli

Marek Novotny

Isaac Rooskov

With contributions from

James Cobb

Cheyenne Weaver

Mark Newton

Steve Ebersole

Daisuke SanoJapanese Translation

Page 4: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Kojiro MiyamotoJapanese Translation

Shoko MiyamotoJapanese Translation

Takeshi MaruyamaJapanese Translation

Yoshiro KanekoJapanese Translation

Ai SuzukiJapanese Translation

Shinobu NogamiJapanese Translation

Junnichi TanabeJapanese Translation

Keita HigashiJapanese Translation

Fusayuki MinamotoJapanese Translation

Takayoshi KimuraJapanese Translation

Takayoshi OsawaJapanese Translation

Reiko OhtsukaJapanese Translation

Syunpei ShiraishiJapanese Translation

Toshiya KobayashiJapanese Translation

Shigeaki WakizakaJapanese Translation

Ken YamadaJapanese Translation

Noriko Mizumoto

Legal Notice

Copyright © 2011 Red Hat, Inc.

This document is licensed by Red Hat under the Creative Commons Attribution-ShareAlike 3.0Unported License. If you distribute this document, or a modified version of it, you must provideattribution to Red Hat, Inc. and provide a link to the original. If the document is modified, all RedHat trademarks must be removed.

Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert,Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.

Red Hat, Red Hat Enterprise Linux, the Shadowman logo, JBoss, OpenShift, Fedora, the Infinitylogo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and othercountries.

Linux ® is the registered trademark of Linus Torvalds in the United States and other countries.

Java ® is a registered trademark of Oracle and/or its affiliates.

XFS ® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the UnitedStates and/or other countries.

MySQL ® is a registered trademark of MySQL AB in the United States, the European Union andother countries.

Node.js ® is an official trademark of Joyent. Red Hat Software Collections is not formally relatedto or endorsed by the official Joyent Node.js open source or commercial project.

The OpenStack ® Word Mark and OpenStack logo are either registered trademarks/service marksor trademarks/service marks of the OpenStack Foundation, in the United States and othercountries and are used with the OpenStack Foundation's permission. We are not affiliated with,endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.

All other trademarks are the property of their respective owners.

Abstract

This book is a Reference Guide to Seam 2.0.2 for use with JBoss Enterprise Application Platform4.3 and its patch releases.

Page 5: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Japanese Translation

Page 6: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Table of Contents

INTRODUCTION TO JBOSS SEAM

CHAPTER 1. SEAM TUTORIAL1.1. TRY THE EXAMPLES

1.1.1. Running the examples on JBoss AS1.2. YOUR FIRST SEAM APPLICATION: THE REGISTRATION EXAMPLE

1.2.1. Understanding the code1.2.1.1. The entity bean: User.java1.2.1.2. The stateless session bean class: RegisterAction.java1.2.1.3. The session bean local interface: Register.java1.2.1.4. The Seam component deployment descriptor: components.xml1.2.1.5. The web deployment description: web.xml1.2.1.6. The JSF configuration: faces-config.xml1.2.1.7. The EJB deployment descriptor: ejb-jar.xml1.2.1.8. The EJB persistence deployment descriptor: persistence.xml1.2.1.9. The view: register.xhtml and registered.xhtml1.2.1.10. The EAR deployment descriptor: application.xml

1.2.2. How it works1.3. CLICKABLE LISTS IN SEAM: THE MESSAGES EXAMPLE

1.3.1. Understanding the code1.3.1.1. The entity bean: Message.java1.3.1.2. The stateful session bean: MessageManagerBean.java1.3.1.3. The session bean local interface: MessageManager.java1.3.1.4. The view: messages.jsp

1.3.2. How it works1.4. SEAM AND JBPM: THE TODO LIST EXAMPLE

1.4.1. Understanding the code1.5. SEAM PAGEFLOW: THE NUMBERGUESS EXAMPLE

1.5.1. Understanding the code1.6. A COMPLETE SEAM APPLICATION: THE HOTEL BOOKING EXAMPLE

1.6.1. Introduction1.6.2. Overview of the booking example1.6.3. Understanding Seam conversations1.6.4. The Seam UI control library1.6.5. The Seam Debug Page

1.7. A COMPLETE APPLICATION FEATURING SEAM AND JBPM: THE DVD STORE EXAMPLE1.8. AN EXAMPLE OF SEAM WITH HIBERNATE: THE HIBERNATE BOOKING EXAMPLE1.9. A RESTFUL SEAM APPLICATION: THE BLOG EXAMPLE

1.9.1. Using "pull"-style MVC1.9.2. Bookmarkable search results page1.9.3. Using "push"-style MVC in a RESTful application

CHAPTER 2. GETTING STARTED WITH SEAM, USING SEAM-GEN2.1. BEFORE YOU START2.2. SETTING UP A NEW ECLIPSE PROJECT2.3. CREATING A NEW ACTION2.4. CREATING A FORM WITH AN ACTION2.5. GENERATING AN APPLICATION FROM AN EXISTING DATABASE2.6. GENERATING AN APPLICATION FROM EXISTING JPA/EJB3 ENTITIES2.7. DEPLOYING THE APPLICATION AS AN EAR2.8. SEAM AND INCREMENTAL HOT DEPLOYMENT

11

15151515161618

2020212222232324252526262729293031313637434344455252535555565760

626262656667676768

Table of Contents

1

Page 7: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS3.1. BEFORE YOU START3.2. SETTING UP A NEW SEAM PROJECT3.3. CREATING A NEW ACTION3.4. CREATING A FORM WITH AN ACTION3.5. GENERATING AN APPLICATION FROM AN EXISTING DATABASE3.6. SEAM AND INCREMENTAL HOT DEPLOYMENT WITH JBOSS TOOLS

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 24.1. CREATING A NEW PROJECT SKELETON USING SEAM-GEN4.2. IN PLACE MIGRATION

4.2.1. Migrating to JSF 1.24.2.2. Migrating web.xml to Seam 24.2.3. Migrating faces-config.xml to Seam 24.2.4. Deployment structure changes4.2.5. Migration to JBoss Embedded

4.3. UPDATING YOUR CODE4.3.1. Built-in Component changes4.3.2. Annotation changes in Seam 24.3.3. Other changes needed to components.xml4.3.4. Migration to jBPM 3.24.3.5. Migration to RichFaces 3.14.3.6. Changes to Seam UI4.3.7. Changes to seam-gen

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL5.1. SEAM CONTEXTS

5.1.1. Stateless context5.1.2. Event context5.1.3. Page context5.1.4. Conversation context5.1.5. Session context5.1.6. Business process context5.1.7. Application context5.1.8. Context variables5.1.9. Context search priority5.1.10. Concurrency model

5.2. SEAM COMPONENTS5.2.1. Stateless session beans5.2.2. Stateful session beans5.2.3. Entity beans5.2.4. JavaBeans5.2.5. Message-driven beans5.2.6. Interception5.2.7. Component names5.2.8. Defining the component scope5.2.9. Components with multiple roles5.2.10. Built-in components

5.3. BIJECTION5.4. LIFECYCLE METHODS5.5. CONDITIONAL INSTALLATION5.6. LOGGING5.7. THE MUTABLE INTERFACE AND @READONLY

70707082848586

88888888899091919292979898989999

101101101101102102102103103103103104104104105105106106106107108108108109

111112113114

Seam 2 Reference Guide

2

Page 8: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5.8. FACTORY AND MANAGER COMPONENTS

CHAPTER 6. CONFIGURING SEAM COMPONENTS6.1. CONFIGURING COMPONENTS VIA PROPERTY SETTINGS6.2. CONFIGURING COMPONENTS VIA COMPONENTS.XML6.3. FINE-GRAINED CONFIGURATION FILES6.4. CONFIGURABLE PROPERTY TYPES6.5. USING XML NAMESPACES

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING7.1. SEAM EVENTS7.2. PAGE ACTIONS7.3. PAGE PARAMETERS

7.3.1. Mapping request parameters to the model7.4. PROPAGATING REQUEST PARAMETERS7.5. CONVERSION AND VALIDATION7.6. NAVIGATION7.7. FINE-GRAINED FILES FOR DEFINITION OF NAVIGATION, PAGE ACTIONS AND PARAMETERS7.8. COMPONENT-DRIVEN EVENTS7.9. CONTEXTUAL EVENTS7.10. SEAM INTERCEPTORS7.11. MANAGING EXCEPTIONS

7.11.1. Exceptions and transactions7.11.2. Enabling Seam exception handling7.11.3. Using annotations for exception handling7.11.4. Using XML for exception handling7.11.5. Some common exceptions

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT8.1. SEAM'S CONVERSATION MODEL8.2. NESTED CONVERSATIONS8.3. STARTING CONVERSATIONS WITH GET REQUESTS8.4. USING <S:LINK> AND <S:BUTTON>8.5. SUCCESS MESSAGES8.6. NATURAL CONVERSATION IDS8.7. CREATING A NATURAL CONVERSATION8.8. REDIRECTING TO A NATURAL CONVERSATION8.9. WORKSPACE MANAGEMENT

8.9.1. Workspace management and JSF navigation8.9.2. Workspace management and jPDL pageflow8.9.3. The conversation switcher8.9.4. The conversation list8.9.5. Breadcrumbs

8.10. CONVERSATIONAL COMPONENTS AND JSF COMPONENT BINDINGS8.11. CONCURRENT CALLS TO CONVERSATIONAL COMPONENTS

8.11.1. How should we design our conversational AJAX application?8.11.2. Dealing with errors8.11.3. RichFaces Ajax

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES9.1. PAGEFLOW IN SEAM

9.1.1. The two navigation models9.1.2. Seam and the back button

9.2. USING JPDL PAGEFLOWS

115

118118118121122123

127127127128128129129130133133135137138138139139140141

143143145145146147148149149150150151151152153153154155155156

158158158161162

Table of Contents

3

Page 9: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9.2.1. Installing pageflows9.2.2. Starting pageflows9.2.3. Page nodes and transitions9.2.4. Controlling the flow9.2.5. Ending the flow9.2.6. Pageflow composition

9.3. BUSINESS PROCESS MANAGEMENT IN SEAM9.4. USING JPDL BUSINESS PROCESS DEFINITIONS

9.4.1. Installing process definitions9.4.2. Initializing actor ids9.4.3. Initiating a business process9.4.4. Task assignment9.4.5. Task lists9.4.6. Performing a task

CHAPTER 10. SEAM AND OBJECT/RELATIONAL MAPPING10.1. INTRODUCTION10.2. SEAM MANAGED TRANSACTIONS

10.2.1. Disabling Seam-managed transactions10.2.2. Configuring a Seam transaction manager10.2.3. Transaction synchronization

10.3. SEAM-MANAGED PERSISTENCE CONTEXTS10.3.1. Using a Seam-managed persistence context with JPA10.3.2. Using a Seam-managed Hibernate session10.3.3. Seam-managed persistence contexts and atomic conversations

10.4. USING THE JPA DELEGATE10.5. USING EL IN EJB-QL/HQL10.6. USING HIBERNATE FILTERS

CHAPTER 11. JSF FORM VALIDATION IN SEAM

CHAPTER 12. GROOVY INTEGRATION12.1. GROOVY INTRODUCTION12.2. WRITING SEAM APPLICATIONS IN GROOVY

12.2.1. Writing Groovy components12.2.1.1. Entity12.2.1.2. Seam component

12.2.2. seam-gen12.3. DEPLOYMENT

12.3.1. Deploying Groovy code12.3.2. Native .groovy file deployment at development time12.3.3. seam-gen

CHAPTER 13. THE SEAM APPLICATION FRAMEWORK13.1. INTRODUCTION13.2. HOME OBJECTS13.3. QUERY OBJECTS13.4. CONTROLLER OBJECTS

CHAPTER 14. SEAM AND JBOSS RULES14.1. INSTALLING RULES14.2. USING RULES FROM A SEAM COMPONENT14.3. USING RULES FROM A JBPM PROCESS DEFINITION

CHAPTER 15. SECURITY

162163163164165165165166166167167167167168

170170170171171

172173173173174175176176

178

183183183183183184185185185185186

187187188192195

196196197197

200

Seam 2 Reference Guide

4

Page 10: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

15.1. OVERVIEW15.1.1. Which mode is right for my application?

15.2. REQUIREMENTS15.3. DISABLING SECURITY15.4. AUTHENTICATION

15.4.1. Configuration15.4.2. Writing an authentication method

15.4.2.1. Identity.addRole()15.4.2.2. Special Considerations

15.4.3. Writing a login form15.4.4. Simplified Configuration - Summary15.4.5. Handling Security Exceptions15.4.6. Login Redirection15.4.7. HTTP Authentication

15.4.7.1. Writing a Digest Authenticator15.4.8. Advanced Authentication Features

15.4.8.1. Using your container's JAAS configuration15.5. ERROR MESSAGES15.6. AUTHORIZATION

15.6.1. Core concepts15.6.2. Securing components

15.6.2.1. The @Restrict annotation15.6.2.2. Inline restrictions

15.6.3. Security in the user interface15.6.4. Securing pages15.6.5. Securing Entities

15.6.5.1. Entity security with JPA15.6.5.2. Entity security with a Managed Hibernate Session

15.7. WRITING SECURITY RULES15.7.1. Permissions Overview15.7.2. Configuring a rules file15.7.3. Creating a security rules file

15.7.3.1. Wildcard permission checks15.8. SSL SECURITY15.9. CAPTCHA

15.9.1. Configuring the CAPTCHA Servlet15.9.2. Adding a CAPTCHA to a form15.9.3. Customizing the CAPTCHA algorithm

15.10. SECURITY EVENTS15.11. RUN AS15.12. EXTENDING THE IDENTITY COMPONENT

CHAPTER 16. INTERNATIONALIZATION, LOCALIZATION AND THEMES16.1. INTERNATIONALIZING YOUR APP

16.1.1. Application server configuration16.1.2. Translated application strings16.1.3. Other encoding settings

16.2. LOCALES16.3. LABELS

16.3.1. Defining labels16.3.2. Displaying labels16.3.3. Faces messages

16.4. TIMEZONES

200200200200201201201202203203204204205205206206206207207207207207209209210210212213213213213214215216216217217217218218219

221221221221222222223223224224224

Table of Contents

5

Page 11: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16.5. THEMES16.6. PERSISTING LOCALE AND THEME PREFERENCES VIA COOKIES

CHAPTER 17. SEAM TEXT17.1. BASIC FORMATTING17.2. ENTERING CODE AND TEXT WITH SPECIAL CHARACTERS17.3. LINKS17.4. ENTERING HTML

CHAPTER 18. ITEXT PDF GENERATION18.1. USING PDF SUPPORT

18.1.1. Creating a document18.1.2. Basic Text Elements18.1.3. Headers and Footers18.1.4. Chapters and Sections18.1.5. Lists18.1.6. Tables18.1.7. Document Constants

18.1.7.1. Color Values18.1.7.2. Alignment Values

18.1.8. Configuring iText18.2. CHARTING18.3. BAR CODES18.4. RENDERING SWING/AWT COMPONENTS18.5. FURTHER DOCUMENTATION

CHAPTER 19. EMAIL19.1. CREATING A MESSAGE

19.1.1. Attachments19.1.2. HTML/Text alternative part19.1.3. Multiple recipients19.1.4. Multiple messages19.1.5. Templates19.1.6. Internationalization19.1.7. Other Headers

19.2. RECEIVING EMAILS19.3. CONFIGURATION

19.3.1. mailSession19.3.1.1. JNDI lookup in JBoss AS19.3.1.2. Seam configured Session

19.4. TAGS

CHAPTER 20. ASYNCHRONOUS AND MESSAGING20.1. ASYNCHRONOUSLY

20.1.1. Asynchronous methods20.1.2. Asynchronous methods with the Quartz Dispatcher20.1.3. Asynchronous events

20.2. MESSAGING IN SEAM20.2.1. Configuration20.2.2. Sending messages20.2.3. Receiving messages using a message-driven bean20.2.4. Receiving messages in the client

CHAPTER 21. CACHING

225226

227227228229230

231231231232236238240242244244245245245255256257

258258259260260260261261261262263263263263264

267267267270272272272272273273

274

Seam 2 Reference Guide

6

Page 12: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21.1. USING JBOSSCACHE IN SEAM21.2. PAGE FRAGMENT CACHING

CHAPTER 22. WEB SERVICES22.1. CONFIGURATION AND PACKAGING22.2. CONVERSATIONAL WEB SERVICES

22.2.1. A Recommended Strategy22.3. AN EXAMPLE WEB SERVICE

CHAPTER 23. REMOTING23.1. CONFIGURATION23.2. THE "SEAM" OBJECT

23.2.1. A Hello World example23.2.2. Seam.Component

23.2.2.1. Seam.Component.newInstance()23.2.2.2. Seam.Component.getInstance()23.2.2.3. Seam.Component.getComponentName()

23.2.3. Seam.Remoting23.2.3.1. Seam.Remoting.createType()23.2.3.2. Seam.Remoting.getTypeName()

23.3. EVALUATING EL EXPRESSIONS23.4. CLIENT INTERFACES23.5. THE CONTEXT

23.5.1. Setting and reading the Conversation ID23.5.2. Remote calls within the current conversation scope

23.6. BATCH REQUESTS23.7. WORKING WITH DATA TYPES

23.7.1. Primitives / Basic Types23.7.1.1. String23.7.1.2. Number23.7.1.3. Boolean

23.7.2. JavaBeans23.7.3. Dates and Times23.7.4. Enums23.7.5. Collections

23.7.5.1. Bags23.7.5.2. Maps

23.8. DEBUGGING23.9. THE LOADING MESSAGE

23.9.1. Changing the message23.9.2. Hiding the loading message23.9.3. A Custom Loading Indicator

23.10. CONTROLLING WHAT DATA IS RETURNED23.10.1. Constraining normal fields23.10.2. Constraining Maps and Collections23.10.3. Constraining objects of a specific type23.10.4. Combining Constraints

23.11. JMS MESSAGING23.11.1. Configuration23.11.2. Subscribing to a JMS Topic23.11.3. Unsubscribing from a Topic23.11.4. Tuning the Polling Process

CHAPTER 24. SPRING FRAMEWORK INTEGRATION

274275

277277277278278

281281282282283283284284285285285285285286286286287287287287287287287288288288288289289289289289290290290291291291291292292292292

294

Table of Contents

7

Page 13: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

24.1. INJECTING SEAM COMPONENTS INTO SPRING BEANS24.2. INJECTING SPRING BEANS INTO SEAM COMPONENTS24.3. MAKING A SPRING BEAN INTO A SEAM COMPONENT24.4. SEAM-SCOPED SPRING BEANS24.5. USING SPRING PLATFORMTRANSACTIONMANAGEMENT24.6. USING A SEAM MANAGED PERSISTENCE CONTEXT IN SPRING24.7. USING A SEAM MANAGED HIBERNATE SESSION IN SPRING24.8. SPRING APPLICATION CONTEXT AS A SEAM COMPONENT24.9. USING A SPRING TASKEXECUTOR FOR @ASYNCHRONOUS

CHAPTER 25. HIBERNATE SEARCH25.1. INTRODUCTION25.2. CONFIGURATION25.3. USAGE

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS26.1. BASIC SEAM CONFIGURATION

26.1.1. Integrating Seam with JSF and your servlet container26.1.2. Using facelets26.1.3. Seam Resource Servlet26.1.4. Seam servlet filters

26.1.4.1. Exception handling26.1.4.2. Conversation propagation with redirects26.1.4.3. Multipart form submissions26.1.4.4. Character encoding26.1.4.5. RichFaces26.1.4.6. Identity Logging26.1.4.7. Context management for custom servlets26.1.4.8. Adding custom filters

26.1.5. Integrating Seam with your EJB container26.1.6. The Final Item

26.2. USING ALTERNATE JPA PROVIDERS26.3. CONFIGURING SEAM IN JAVA EE 5

26.3.1. Packaging26.4. CONFIGURING SEAM IN J2EE

26.4.1. Boostrapping Hibernate in Seam26.4.2. Boostrapping JPA in Seam26.4.3. Packaging

26.5. CONFIGURING SEAM IN JAVA SE, WITHOUT JBOSS EMBEDDED26.6. CONFIGURING JBPM IN SEAM

26.6.1. Packaging26.7. CONFIGURING SFSB AND SESSION TIMEOUTS IN JBOSS AS26.8. RUNNING SEAM IN A PORTLET

CHAPTER 27. SEAM ANNOTATIONS27.1. ANNOTATIONS FOR COMPONENT DEFINITION27.2. ANNOTATIONS FOR BIJECTION27.3. ANNOTATIONS FOR COMPONENT LIFECYCLE METHODS27.4. ANNOTATIONS FOR CONTEXT DEMARCATION27.5. ANNOTATIONS FOR USE WITH SEAM JAVABEAN COMPONENTS IN A J2EE ENVIRONMENT27.6. ANNOTATIONS FOR EXCEPTIONS27.7. ANNOTATIONS FOR SEAM REMOTING27.8. ANNOTATIONS FOR SEAM INTERCEPTORS27.9. ANNOTATIONS FOR ASYNCHRONOUSLY

294295296296297298299300300

301301301302

305305305306306306307307307308308309309309310311311312312313314314314315315316317318

319319322324325328329330330330

Seam 2 Reference Guide

8

Page 14: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27.10. ANNOTATIONS FOR USE WITH JSF27.10.1. Annotations for use with dataTable

27.11. META-ANNOTATIONS FOR DATABINDING27.12. ANNOTATIONS FOR PACKAGING27.13. ANNOTATIONS FOR INTEGRATING WITH THE SERVLET CONTAINER

CHAPTER 28. BUILT-IN SEAM COMPONENTS28.1. CONTEXT INJECTION COMPONENTS28.2. UTILITY COMPONENTS28.3. COMPONENTS FOR INTERNATIONALIZATION AND THEMES28.4. COMPONENTS FOR CONTROLLING CONVERSATIONS28.5. JBPM-RELATED COMPONENTS28.6. SECURITY-RELATED COMPONENTS28.7. JMS-RELATED COMPONENTS28.8. MAIL-RELATED COMPONENTS28.9. INFRASTRUCTURAL COMPONENTS28.10. MISCELLANEOUS COMPONENTS28.11. SPECIAL COMPONENTS

CHAPTER 29. SEAM JSF CONTROLS29.1. TAGS

29.1.1. Navigation Controls29.1.1.1. <s:button>29.1.1.2. <s:conversationId>29.1.1.3. <s:taskId>29.1.1.4. <s:link>29.1.1.5. <s:conversationPropagation>29.1.1.6. <s:defaultAction>

29.1.2. Converters and Validators29.1.2.1. <s:convertDateTime>29.1.2.2. <s:convertEntity>29.1.2.3. <s:convertEnum>29.1.2.4. <s:validate>29.1.2.5. <s:validateAll>

29.1.3. Formatting29.1.3.1. <s:decorate>29.1.3.2. <s:div>29.1.3.3. <s:span>29.1.3.4. <s:fragment>29.1.3.5. <s:label>29.1.3.6. <s:message>

29.1.4. Seam Text29.1.4.1. <s:validateFormattedText>29.1.4.2. <s:formattedText>

29.1.5. Dropdowns29.1.5.1. <s:enumItem>29.1.5.2. <s:selectItems>

29.1.6. Other29.1.6.1. <s:cache>29.1.6.2. <s:fileUpload>29.1.6.3. <s:graphicImage>29.1.6.4. <s:remote>

29.2. ANNOTATIONS

331332332333333

334334334336337338340340341341343344

346346346346346347347347348348348349350350350351351352352352353353353353354354354355355355356357358358

Table of Contents

9

Page 15: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CHAPTER 30. JBOSS EL30.1. PARAMETRIZED EXPRESSIONS

30.1.1. Usage30.1.2. Limitations and Hints

30.2. PROJECTION

CHAPTER 31. TESTING SEAM APPLICATIONS31.1. UNIT TESTING SEAM COMPONENTS31.2. INTEGRATION TESTING SEAM COMPONENTS

31.2.1. Using mocks in integration tests31.3. INTEGRATION TESTING SEAM APPLICATION USER INTERACTIONS

31.3.1. Configuration31.3.2. Using SeamTest with another test framework31.3.3. Integration Testing with Mock Data31.3.4. Integration Testing Seam Mail

CHAPTER 32. SEAM TOOLS32.1. JBPM DESIGNER AND VIEWER

32.1.1. Business process designer32.1.2. Pageflow viewer

CHAPTER 33. DEPENDENCIES33.1. JDK DEPENDENCIES

33.1.1. Sun's JDK 6 Considerations33.2. PROJECT DEPENDENCIES

33.2.1. Core33.2.2. RichFaces33.2.3. Seam Mail33.2.4. Seam PDF33.2.5. JBoss Rules33.2.6. JBPM33.2.7. GWT33.2.8. Spring33.2.9. Groovy

33.3. DEPENDENCY MANAGEMENT USING MAVEN

APPENDIX A. REVISION HISTORY

360360360361362

364364365366366369370371

372

373373373373

375375375375375376376377377378378378379379

382

Seam 2 Reference Guide

10

Page 16: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

INTRODUCTION TO JBOSS SEAMSeam is an application framework for Enterprise Java. It is inspired by the following principles:

A uniform component model

Seam defines a uniform component model for all business logic in your application. A Seamcomponent may be stateful, with the state associated with any one of several well-defined contexts,including the long-running, persistent, business process context and the conversation context, whichis preserved across multiple web requests in a user interaction.

There is no distinction between presentation tier components and business logic components inSeam. Your application can be layered according to whatever architecture you devise, rather thanforcing your application logic into an unnatural layering scheme forced upon you by whatevercombination of frameworks you are using today.

Unlike plain Java EE or J2EE components, Seam components may simultaneously access the stateassociated with the web request and the state held in transactional resources (without the need topropagate a web request state manually via method parameters). Seam grants you the ability tocreate a layered architecture in the case that the old J2EE platform is not up-to-date with yourneeds. In doing this you get to architect your own application and decide what the layers are andhow they work together.

Integrate JSF with EJB 3.0

JSF and EJB 3.0 are two of the most outstanding new features of Java EE 5. EJB3 is a brand newcomponent model for server side business and persistence logic. Meanwhile, JSF is an excellentcomponent model for the presentation tier. Unfortunately, neither component model is able tosolve all problems in computing by itself. Indeed, JSF and EJB3 work best when used together. Butthe Java EE 5 specification provides no standard way to integrate the two component models.Fortunately, the creators of both models foresaw this situation and provided standard extensionpoints to allow extension and integration with other frameworks.

Seam unifies the component models of JSF and EJB3, eliminating glue code, and allowing thedeveloper to concentrate on the business problem.

It is possible to write Seam applications where everything is an EJB. This may come as a surprise ifyou're used to thinking of EJBs as unrefined objects. However, version 3.0 has completely changedthe nature of EJB from the point of view of the developer. An EJB is a refined object; nothing morecomplex than an annotated JavaBean. Furthermore it is encouraged that sessions beans are usedas JSF action listeners.

On the other hand, if you prefer not to adopt EJB 3.0 at this time, you don't have to. Virtually anyJava class may be a Seam component, and Seam provides all the functionality that you expect froma simplistic container (and more) for any component, EJB or otherwise.

Integrated AJAX

Seam supports the finest open source JSF-based AJAX solutions: JBoss RichFaces and ICEfaces.These solutions allow you to add AJAX capability to your user interface without the need to writeany JavaScript code.

INTRODUCTION TO JBOSS SEAM

11

Page 17: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

NOTE

Icefaces integration in Seam is marked as technology preview, so standard support isnot guaranteed.

Alternatively, Seam provides a built-in JavaScript remoting layer that lets you call componentsasynchronously from client-side JavaScript without the need for an intermediate action layer. Youcan even subscribe to server-side JMS topics and receive messages via AJAX push.

Neither of these approaches would work well, were it not for Seam's built-in concurrency and statemanagement, which ensures that many concurrent, asynchronous AJAX requests are handledsafely and efficiently on the server side.

Business process as a first class construct

Optionally, Seam provides transparent business process management via jBPM allowing forimplemention of complex workflows, collaboration and task management using jBPM and Seam tobe relatively simple.

Seam even allows you to define presentation tier pageflow using the same language (jPDL) thatjBPM uses for business process definition.

JSF provides an incredibly rich event model for the presentation tier. Seam enhances this model byexposing jBPM's business process related events via exactly the same event handling mechanism,providing a uniform event model for Seam's uniform component model.

Declarative state management

The concept of declarative transaction management and declarative security has been presentsince the early days of EJB. EJB 3.0 now introduces declarative persistence context management.These are three examples of a broader problem of managing state that is associated with aparticular context, while ensuring that all needed cleanup occurs when the context ends. Seamtakes the concept of declarative state management much further and applies it to application state.Traditionally, J2EE applications implement state management manually, by getting and settingservlet session and request attributes. This approach to state management is the source of manybugs and memory leaks when applications fail to clean up session attributes, or when session dataassociated with different workflows collides in a multi-window application. Seam has the potentialto almost entirely eliminate this class of bugs.

Declarative application state management is made possible by the richness of the context modeldefined by Seam. Seam extends the context model defined by the servlet spec (request, session,application) with two new contexts (conversation and business process) that are more meaningfulfrom the point of view of the business logic.

You will be amazed at how many things become easier once you start using conversations. Haveyou ever suffered pain dealing with lazy association fetching in an ORM solution like Hibernate orJPA? Seam's conversation-scoped persistence contexts mean you will rarely have to see a LazyInitializationException. Have you ever had problems with the refresh button? Theback button? With duplicate form submission? With propagating messages across a post-then-redirect? Seam's conversation management solves these problems without you even needing toreally think about them. They're all symptoms of the broken state management architecture thathas been prevalent since the earliest days of the web.

Bijection

The notion of Inversion of Control or dependency injection exists in both JSF and EJB3, as well as innumerous simplistic containers. Most of these containers emphasize injection of components that

Seam 2 Reference Guide

12

Page 18: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

implement stateless services. Even when injection of stateful components is supported (such as inJSF), it is virtually useless for handling application state because the scope of the statefulcomponent cannot be defined with sufficient flexibility, and because components belonging towider scopes may not be injected into components belonging to narrower scopes.

Bijection differs from IoC in that it is dynamic, contextual, and bidirectional. You can think of it as amechanism for aliasing contextual variables (names in the various contexts bound to the currentthread) to attributes of the component. Bijection allows auto-assembly of stateful components bythe container. It even allows a component to safely and easily manipulate the value of a contextvariable, just by assigning it to an attribute of the component.

Workspace management and multi-window browsing

Seam applications let the user freely switch between multiple browser tabs, each associated with adifferent, safely isolated, conversation. Applications may even take advantage of workspacemanagement, allowing the user to switch between conversations (workspaces) in a single browsertab. Seam provides not only correct multi-window operation, but also multi-window-like operationwithin a single window.

Prefer annotations to XML

Traditionally, the Java community has been in a state of deep confusion about precisely what kindof meta-information counts as configuration. J2EE and popular simplistic containers have providedXML-based deployment descriptors for code which is truly configurable between differentdeployments of the system, and for all other kinds or declarations which can not easily beexpressed in Java; Java 5 annotations changed all this.

EJB 3.0 embraces annotations and configuration by exception as the easiest way to provideinformation to the container in a declarative form. Unfortunately, JSF is still heavily dependent onverbose XML configuration files. Seam extends the annotations provided by EJB 3.0 with a set ofannotations for declarative state management and declarative context demarcation. This allows forthe elimination of the noisy JSF managed bean declarations and reduces the required XML to justthat information which truly belongs in XML (the JSF navigation rules).

Integration testing is easy

Seam components, being plain Java classes, are by nature unit testable. But for complexapplications, unit testing alone is insufficient. Integration testing has traditionally been a messy anddifficult task for Java web applications. Therefore, Seam provides for testability of Seamapplications as a core feature of the framework. You can easily write JUnit or TestNG tests thatreproduce a whole interaction with a user, exercising all components of the system apart from theview (the JSP or Facelets page). You can run these tests directly inside your IDE, where Seam willautomatically deploy EJB components using JBoss Embedded.

Improving upon Java EE

The latest incarnation of Java EE is a great step forward and we know it's never going to be perfect.Where there are holes in the specifications (for example, limitations in the JSF lifecycle for GETrequests), Seam fixes them. And the authors of Seam are working with the JCP expert groups tomake sure those fixes make their way back into the next revision of the standards.

There's more to a web application than serving HTML pages

Today's web frameworks think too small. They let you get user input off a form and into your Javaobjects. A truly complete web application framework should address problems like persistence,concurrency, asynchronously, state management, security, email, messaging, PDF and chartgeneration, workflow, wikitext rendering, webservices, caching and more. Once you scratch thesurface of Seam, you'll be amazed at how many problems become simpler.

INTRODUCTION TO JBOSS SEAM

13

Page 19: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam integrates JPA and Hibernate3 for persistence, the EJB Timer Service and Quartz for simpleasynchronous operations, jBPM for workflow, Meldware Mail for email, Hibernate Search andLucene for full text search, JMS for messaging, JBoss Cache for page fragment caching and JBossRules for business rules, layering an innovative rule-based security framework over JAAS andJBoss Rules. Also included is JSF tag libraries for rendering PDF, outgoing email, charts andwikitext. Seam components may be called synchronously as a Web Service, asynchronously fromclient-side JavaScript or Google Web Toolkit or, of course, directly from JSF.

Get started now!

Seam works in any Java EE application server, and even works in Tomcat. If your environmentsupports EJB 3.0, great! If it doesn't, no problem, you can use Seam's built-in transactionmanagement with JPA or Hibernate3 for persistence. Or, you can deploy JBoss Embedded inTomcat, and get full support for EJB 3.0.

It turns out that the combination of Seam, JSF and EJB3 is the simplest way to write a complex webapplication in Java. You won't believe how little code is required!

Seam 2 Reference Guide

14

Page 20: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 1. SEAM TUTORIAL

1.1. TRY THE EXAMPLES

In this tutorial, we will assume that you are using JBoss EAP 4.3.

The directory structure of each example in Seam follows this pattern:

Web pages, images and stylesheets may be found in examples/registration/view

Resources such as deployment descriptors and data import scripts may be found in examples/registration/resources

Java source code may be found in examples/registration/src

The Ant build script is examples/registration/build.xml

1.1.1. Running the examples on JBoss AS

First, make sure you have Ant correctly installed, with $ANT_HOME and $JAVA_HOME set correctly.Next, make sure you set the location of your EAP embedded JBoss AS installation in the build.properties file in the root folder of your Seam installation, predefined location is/var/lib/jboss-as. If you haven't already done so, start JBoss AS now by typing bin/run.sh or bin/run.bat in the root directory of your JBoss installation.

Now, build and deploy the example by typing ant deploy in the examples/registrationdirectory.

Try it out by accessing http://localhost:8080/seam-registration/ with your web browser.

1.2. YOUR FIRST SEAM APPLICATION: THE REGISTRATION EXAMPLE

The registration example is a fairly trivial application that lets a new user store his username, realname and password in the database. The example isn't intended to show off all of the interestingfunctionality of Seam. However, it demonstrates the use of an EJB3 session bean as a JSF actionlistener, and basic configuration of Seam.

We will go slowly, so you can become familiar with EJB 3.0.

The start page displays a very basic form with three input fields. Try filling them in and then submittingthe form. This will save a user object in the database.

CHAPTER 1. SEAM TUTORIAL

15

Page 21: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.2.1. Understanding the code

The example is implemented with two JSP pages, one entity bean and one stateless session bean.

Let's take a look at the code, starting from the "bottom".

1.2.1.1. The entity bean: User.java

Seam 2 Reference Guide

16

Page 22: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We need an EJB entity bean for user data. This class defines persistence and validation decoratively, viaannotations. It also needs some extra annotations that define the class as a Seam component.

@Entity <co id="registration-entity-annotation"/>@Name("user")@Scope(SESSION)@Table(name="users")public class User implements Serializable{ private static final long serialVersionUID = 1881413500711441951L; private String username; private String password; private String name; public User(String name, String password, String username) { this.name = name; this.password = password; this.username = username; } public User() {} @NotNull @Length(min=5, max=15) public String getPassword() { return password; }

public void setPassword(String password) { this.password = password; } @NotNull public String getName() { return name; }

public void setName(String name) { this.name = name; } @Id @NotNull @Length(min=5, max=15) public String getUsername() { return username; }

public void setUsername(String username) { this.username = username;

CHAPTER 1. SEAM TUTORIAL

17

Page 23: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The EJB3 standard @Entity annotation indicates that the User class is an entity bean.

A Seam component needs a component name specified by the @Name annotation. This name must beunique within the Seam application. When JSF asks Seam to resolve a context variable with a namethat is the same as a Seam component name, and the context variable is currently undefined (null),Seam will instantiate that component, and bind the new instance to the context variable. In this case,Seam will instantiate a User the first time JSF encounters a variable named user.

Whenever Seam instantiates a component, it binds the new instance to a context variable in thecomponent's default context. The default context is specified using the @Scope annotation. The Userbean is a session scoped component.

The EJB standard @Table annotation indicates that the User class is mapped to the users table.

name, password and username are the persistent attributes of the entity bean. All of our persistentattributes define accessor methods. These are needed when this component is used by JSF in therender response and update model values phases.

An empty constructor is required by both the EJB specification and by Seam.

The @NotNull and @Length annotations are part of the Hibernate Validator framework. Seamintegrates Hibernate Validator and lets you use it for data validation (even if you are not usingHibernate for persistence).

The EJB standard @Id annotation indicates the primary key attribute of the entity bean.

The most important things to notice in this example are the @Name and @Scope annotations. Theseannotations establish that this class is a Seam component.

We will see below that the properties of our User class are bound directly to JSF components and arepopulated by JSF during the update model values phase. We don't need any tedious glue code to copydata back and forth between the JSP pages and the entity bean domain model.

However, entity beans shouldn't do transaction management or database access. So we can't use thiscomponent as a JSF action listener. For that we need a session bean.

1.2.1.2. The stateless session bean class: RegisterAction.java

Most Seam application use session beans as JSF action listeners (you can use JavaBeans instead if youlike).

We have exactly one JSF action in our application, and one session bean method attached to it. In thiscase, we'll use a stateless session bean, since all the state associated with our action is held by the User bean.

This is the only really interesting code in the example!

}

}

@Stateless@Name("register")public class RegisterAction implements Register{

Seam 2 Reference Guide

18

Page 24: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The EJB standard @Stateless annotation marks this class as a stateless session bean.

The @In annotation marks an attribute of the bean as injected by Seam. In this case, the attribute isinjected from a context variable named user (the instance variable name).

The EJB standard @PersistenceContext annotation is used to inject the EJB3 entity manager.

The Seam @Logger annotation is used to inject the component's Log instance.

The action listener method uses the standard EJB3 EntityManager API to interact with thedatabase, and returns the JSF outcome. Note that, since this is a session bean, a transaction isautomatically begun when the register() method is called, and committed when it completes.

Notice that Seam lets you use a JSF EL expression inside EJB-QL. Under the covers, this results in anordinary JPA setParameter() call on the standard JPA Query object. Nice, huh?

The Log API lets us easily display log messages created from templates.

JSF action listener methods return a string-valued outcome that determines what page will bedisplayed next. A null outcome (or a void action listener method) re-displays the previous page. In plainJSF, it is normal to always use a JSF navigation rule to determine the JSF view id from the outcome. Forcomplex application this indirection is useful and a good practice. However, for very simple exampleslike this one, Seam lets you use the JSF view id as the outcome, eliminating the requirement for anavigation rule. Note that when you use a view id as an outcome, Seam always performs a browser redirect.

@In private User user; @PersistenceContext private EntityManager em; @Logger private Log log; public String register() { List existing = em.createQuery( "select username from User where username=#{user.username}") .getResultList(); if (existing.size()==0) { em.persist(user); log.info("Registered new user #{user.username}"); return "/registered.xhtml"; } else { FacesMessages.instance().add("User #{user.username} already exists"); return null; } }

}

CHAPTER 1. SEAM TUTORIAL

19

Page 25: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam provides a number of built-in components to help solve common problems. The FacesMessagescomponent makes it easy to display template error or success messages. Built-in Seam componentsmay be obtained by injection, or by calling an instance() method.

Note that we did not explicitly specify a @Scope this time. Each Seam component type has a defaultscope if not explicitly specified. For stateless session beans, the default scope is the stateless context.Actually, all stateless session beans belong in the stateless context.

Our session bean action listener performs the business and persistence logic for our mini-application.In more complex applications, we might need to layer the code and refactor persistence logic into adedicated data access component. That's perfectly trivial to do. But notice that Seam does not forceyou into any particular strategy for application layering.

Furthermore, notice that our session bean has simultaneous access to context associated with the webrequest (the form values in the User object, for example), and state held in transactional resources(the EntityManager object). This is a break from traditional J2EE architectures. Again, if you aremore comfortable with the traditional J2EE layering, you can certainly implement that in a Seamapplication. But for many applications, it's simply not very useful.

1.2.1.3. The session bean local interface: Register.java

Naturally, our session bean needs a local interface.

That's the end of the Java code. Now onto the deployment descriptors.

1.2.1.4. The Seam component deployment descriptor: components.xml

If you've used many Java frameworks before, you'll be used to having to declare all your componentclasses in some kind of XML file that gradually grows more and more unmanageable as your projectmatures. You'll be relieved to know that Seam does not require that application components beaccompanied by XML. Most Seam applications require a very small amount of XML that does not growvery much as the project gets bigger.

Nevertheless, it is often useful to be able to provide for some external configuration of somecomponents (particularly the components built in to Seam). You have a couple of options here, but themost flexible option is to provide this configuration in a file called components.xml, located in the WEB-INF directory. We'll use the components.xml file to tell Seam how to find our EJB componentsin JNDI:

@Localpublic interface Register{ public String register();}

<?xml version="1.0" encoding="UTF-8"?><components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.1.xsd http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd">

Seam 2 Reference Guide

20

Page 26: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This code configures a property named jndiPattern of a built-in Seam component named org.jboss.seam.core.init. The funny @ symbols are there because our Ant build script puts thecorrect JNDI pattern in when we deploy the application.

1.2.1.5. The web deployment description: web.xml

The presentation layer for our mini-application will be deployed in a WAR. So we'll need a webdeployment descriptor.

<core:init jndi-pattern="@jndiPattern@"/> </components>

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<listener> <listener-class>org.jboss.seam.servlet.SeamListener</listener-class> </listener>

<listener> <listener-class>com.sun.faces.config.ConfigureListener</listener-class> </listener> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>

<servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.seam</url-pattern> </servlet-mapping> <session-config> <session-timeout>10</session-timeout> </session-config>

</web-app>

CHAPTER 1. SEAM TUTORIAL

21

Page 27: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This web.xml file configures Seam and JSF. The configuration you see here is pretty much identical inall Seam applications.

1.2.1.6. The JSF configuration: faces-config.xml

Most Seam applications use JSF views as the presentation layer. So usually we'll need faces-config.xml. In our case, we are going to use Facelets for defining our views, so we need to tell JSF touse Facelets as its template engine.

Note that we don't need any JSF managed bean declarations! Our managed beans are annotated Seamcomponents. In Seam applications, the faces-config.xml is used much less often than in plain JSF.

In fact, once you have all the basic descriptors set up, the only XML you need to write as you add newfunctionality to a Seam application is orchestration: navigation rules or jBPM process definitions. Seamtakes the view that process flow and configuration data are the only things that truly belong in XML.

In this simple example, we don't even need a navigation rule, since we decided to embed the view id inour action code.

1.2.1.7. The EJB deployment descriptor: ejb-jar.xml

The ejb-jar.xml file integrates Seam with EJB3, by attaching the SeamInterceptor to all sessionbeans in the archive.

<?xml version="1.0" encoding="UTF-8"?><faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

<application> <view-handler>com.sun.facelets.FaceletViewHandler</view-handler> </application> </faces-config>

<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd" version="3.0"> <interceptors> <interceptor> <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class> </interceptor></interceptors> <assembly-descriptor> <interceptor-binding> <ejb-name>*</ejb-name>

Seam 2 Reference Guide

22

Page 28: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.2.1.8. The EJB persistence deployment descriptor: persistence.xml

The persistence.xml file tells the EJB persistence provider where to find the datasource, andcontains some vendor-specific settings. In this case, enables automatic schema export at startup time.

1.2.1.9. The view: register.xhtml and registered.xhtml

The view pages for a Seam application could be implemented using any technology that supports JSF.In this example we use Facelets, because we think it's better than JSP.

<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class> </interceptor-binding></assembly-descriptor> </ejb-jar>

<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

<persistence-unit name="userDatabase"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <property name="hibernate.hbm2ddl.auto" value="create-drop"> </properties></persistence-unit> </persistence>

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:s="http://jboss.com/products/seam/taglib" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core">

<head> <title>Register New User</title></head><body> <f:view> <h:form> <s:validateAll> <h:panelGrid columns="2"> Username: <h:inputText value="#{user.username}" required="true"/> Real Name: <h:inputText value="#{user.name}" required="true"/>

CHAPTER 1. SEAM TUTORIAL

23

Page 29: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The only thing here that is specific to Seam is the <s:validateAll> tag. This JSF component tellsJSF to validate all the contained input fields against the Hibernate Validator annotations specified onthe entity bean.

This is a boring old Facelets page using some embedded EL. There is nothing specific to Seam here.

1.2.1.10. The EAR deployment descriptor: application.xml

Finally, since our application is deployed as an EAR, we need a deployment descriptor there, too.

Password: <h:inputSecret value="#{user.password}" required="true"/> </h:panelGrid> </s:validateAll> <h:messages/> <h:commandButton value="Register" action="#{register.register}"/> </h:form> </f:view></body>

</html>

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"xmlns:f="http://java.sun.com/jsf/core">

<head><title>Successfully Registered New User</title></head><body> <f:view> Welcome, #{user.name}, you are successfully registered as #{user.username}. </f:view></body>

</html>

<?xml version="1.0" encoding="UTF-8"?><application xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd" version="5"> <display-name>Seam Registration</display-name>

<module> <web> <web-uri>jboss-seam-registration.war</web-uri> <context-root>/seam-registration</context-root> </web>

Seam 2 Reference Guide

24

Page 30: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This deployment descriptor links modules in the enterprise archive and binds the web application tothe context root /seam-registration.

We've now seen all the files in the entire application!

1.2.2. How it works

When the form is submitted, JSF asks Seam to resolve the variable named user. Since there is novalue already bound to that name (in any Seam context), Seam instantiates the user component, andreturns the resulting User entity bean instance to JSF after storing it in the Seam session context.

The form input values are now validated against the Hibernate Validator constraints specified on the User entity. If the constraints are violated, JSF re-displays the page. Otherwise, JSF binds the forminput values to properties of the User entity bean.

Next, JSF asks Seam to resolve the variable named register. Seam finds the RegisterActionstateless session bean in the stateless context and returns it. JSF invokes the register() actionlistener method.

Seam intercepts the method call and injects the User entity from the Seam session context, beforecontinuing the invocation.

The register() method checks if a user with the entered username already exists. If so, an errormessage is queued with the FacesMessages component, and a null outcome is returned, causing apage redisplay. The FacesMessages component interpolates the JSF expression embedded in themessage string and adds a JSF FacesMessage to the view.

If no user with that username exists, the "/registered.xhtml" outcome triggers a browser redirectto the registered.xhtml page. When JSF comes to render the page, it asks Seam to resolve thevariable named user and uses property values of the returned User entity from Seam's session scope.

1.3. CLICKABLE LISTS IN SEAM: THE MESSAGES EXAMPLE

Clickable lists of database search results are such an important part of any online application thatSeam provides special functionality on top of JSF to make it easier to query data using EJB-QL or HQLand display it as a clickable list using a JSF <h:dataTable>. The messages example demonstratesthis functionality.

</module><module> <ejb>jboss-seam-registration.jar</ejb></module><module> <ejb>jboss-seam.jar</ejb></module><module> <java>jboss-el.jar</java></module>

</application>

CHAPTER 1. SEAM TUTORIAL

25

Page 31: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.3.1. Understanding the code

The message list example has one entity bean, Message, one session bean, MessageListBean andone JSP.

1.3.1.1. The entity bean: Message.java

The Message entity defines the title, text, date and time of a message, and a flag indicating whetherthe message has been read:

@Entity@Name("message")@Scope(EVENT)public class Message implements Serializable{ private Long id; private String title; private String text; private boolean read; private Date datetime; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; }

Seam 2 Reference Guide

26

Page 32: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.3.1.2. The stateful session bean: MessageManagerBean.java

Just like in the previous example, we have a session bean, MessageManagerBean, which defines theaction listener methods for the two buttons on our form. One of the buttons selects a message fromthe list, and displays that message. The other button deletes a message. So far, this is not so differentto the previous example.

But MessageManagerBean is also responsible for fetching the list of messages the first time wenavigate to the message list page. There are various ways the user could navigate to the page, and notall of them are preceded by a JSF action—the user might have bookmarked the page, for example. Sothe job of fetching the message list takes place in a Seam factory method, instead of in an action listenermethod.

We want to cache the list of messages in memory between server requests, so we will make this astateful session bean.

@NotNull @Length(max=100) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @NotNull @Lob public String getText() { return text; } public void setText(String text) { this.text = text; } @NotNull public boolean isRead() { return read; } public void setRead(boolean read) { this.read = read; } @NotNull @Basic @Temporal(TemporalType.TIMESTAMP) public Date getDatetime() { return datetime; } public void setDatetime(Date datetime) { this.datetime = datetime; } }

@Stateful@Scope(SESSION)@Name("messageManager")

CHAPTER 1. SEAM TUTORIAL

27

Page 33: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The @DataModel annotation exposes an attribute of type java.util.List to the JSF page as aninstance of javax.faces.model.DataModel. This allows us to use the list in a JSF <h:dataTable>with clickable links for each row. In this case, the DataModel is made available in a session contextvariable named messageList.

The @DataModelSelection annotation tells Seam to inject the List element that corresponded tothe clicked link.

The @Out annotation then exposes the selected value directly to the page. So every time a row of theclickable list is selected, the Message is injected to the attribute of the stateful bean, and the result issubsequently passed into the event context variable named message.

This stateful bean has an EJB3 extended persistence context. The messages retrieved in the queryremain in the managed state as long as the bean exists, so any subsequent method calls to the statefulbean can update them without needing to make any explicit call to the EntityManager.

The first time we navigate to the JSP page, there will be no value in the messageList contextvariable. The @Factory annotation tells Seam to create an instance of MessageManagerBean and

public class MessageManagerBean implements Serializable, MessageManager{

@DataModel private List<Message> messageList; @DataModelSelection @Out(required=false) private Message message; @PersistenceContext(type=EXTENDED) private EntityManager em; @Factory("messageList") public void findMessages() { messageList = em.createQuery("from Message msg order by msg.datetime desc") .getResultList(); } public void select() { message.setRead(true); } public void delete() { messageList.remove(message); em.remove(message); message=null; } @Remove public void destroy() {}

}

Seam 2 Reference Guide

28

Page 34: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

invoke the findMessages() method to initialize the value. We call findMessages() a factorymethod for messages.

The select() action listener method marks the selected Message as read, and updates it in thedatabase.

The delete() action listener method removes the selected Message from the database.

All stateful session bean Seam components must have a method with no parameters marked @Removethat Seam uses to remove the stateful bean when the Seam context ends, and clean up any server-sidestate.

Note that this is a session-scoped Seam component. It is associated with the user login session, and allrequests from a login session share the same instance of the component. (In Seam applications, weusually use session-scoped components sparingly.)

1.3.1.3. The session bean local interface: MessageManager.java

All session beans have a business interface, of course.

From now on, we won't show local interfaces in our code examples.

Let's skip over components.xml, persistence.xml, web.xml, ejb-jar.xml, faces-config.xml and application.xml since they are much the same as the previous example, and gostraight to the JSP.

1.3.1.4. The view: messages.jsp

The JSP page is a straightforward use of the JSF <h:dataTable> component. Again, nothing specificto Seam.

@Localpublic interface MessageManager{ public void findMessages(); public void select(); public void delete(); public void destroy();}

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><html> <head> <title>Messages</title> </head> <body> <f:view> <h:form> <h2>Message List</h2> <h:outputText value="No messages to display" rendered="#{messageList.rowCount==0}"/> <h:dataTable var="msg" value="#{messageList}" rendered="#{messageList.rowCount>0}"> <h:column>

CHAPTER 1. SEAM TUTORIAL

29

Page 35: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.3.2. How it works

The first time we navigate to the messages.jsp page, whether by a JSF postback (faces request) or adirect browser GET request (non-faces request), the page will try to resolve the messageList contextvariable. Since this context variable is not initialized, Seam will call the factory method findMessages(), which performs a query against the database and results in a DataModel beingreturned. This DataModel provides the row data needed for rendering the <h:dataTable>.

When the user clicks the <h:commandLink>, JSF calls the select() action listener. Seam interceptsthis call and injects the selected row data into the message attribute of the messageManagercomponent. The action listener fires, marking the selected Message as read. At the end of the call,Seam returns the selected Message to the context variable named message. Next, the EJB containercommits the transaction, and the change to the Message is flushed to the database. Finally, the pageis re-rendered, re-displaying the message list, and displaying the selected message below it.

If the user clicks the <h:commandButton>, JSF calls the delete() action listener. Seam interceptsthis call and injects the selected row data into the message attribute of the messageList component.The action listener fires, removing the selected Message from the list, and also calling remove() onthe EntityManager. At the end of the call, Seam refreshes the messageList context variable andclears the context variable named message. The EJB container commits the transaction, and deletesthe Message from the database. Finally, the page is re-rendered, re-displaying the message list.

<f:facet name="header"> <h:outputText value="Read"/> </f:facet> <h:selectBooleanCheckbox value="#{msg.read}" disabled="true"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Title"/> </f:facet> <h:commandLink value="#{msg.title}" action="#{messageManager.select}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Date/Time"/> </f:facet> <h:outputText value="#{msg.datetime}"> <f:convertDateTime type="both" dateStyle="medium" timeStyle="short"/> </h:outputText> </h:column> <h:column> <h:commandButton value="Delete" action="#{messageManager.delete}"/> </h:column> </h:dataTable> <h3><h:outputTex> value="#{message.title}"/></h3> <div><h:outputText value="#{message.text}"/></div> </h:form> </f:view> </body></html>

Seam 2 Reference Guide

30

Page 36: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.4. SEAM AND JBPM: THE TODO LIST EXAMPLE

jBPM provides sophisticated functionality for workflow and task management. To get a small taste ofhow jBPM integrates with Seam, we'll show you a simple "todo list" application. Since managing lists oftasks is such core functionality for jBPM, there is hardly any Java code at all in this example.

1.4.1. Understanding the code

The center of this example is the jBPM process definition. There are also two JSPs and two trivialJavaBeans (There was no reason to use session beans, since they do not access the database, or haveany other transactional behavior). Let's start with the process definition:

The <start-state> node represents the logical start of the process. When the process starts, itimmediately transitions to the todo node.

The <task-node> node represents a wait state, where business process execution pauses, waiting forone or more tasks to be performed.

<process-definition name="todo"> <start-state name="start"><transition to="todo"/></start-state> <task-node name="todo"><task name="todo" description="#{todoList.description}"><assignment actor-id="#{actor.id}"/></task><transition to="done"/></task-node> <end-state name="done"/> </process-definition>

CHAPTER 1. SEAM TUTORIAL

31

Page 37: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The <task> element defines a task to be performed by a user. Since there is only one task defined onthis node, when it is complete, execution resumes, and we transition to the end state. The task gets itsdescription from a Seam component named todoList (one of the JavaBeans).

Tasks need to be assigned to a user or group of users when they are created. In this case, the task isassigned to the current user, which we get from a built-in Seam component named actor. Any Seamcomponent may be used to perform task assignment.

The <end-state> node defines the logical end of the business process. When execution reaches thisnode, the process instance is destroyed.

If we view this process definition using the process definition editor provided by JBossIDE, this is whatit looks like:

This document defines our business process as a graph of nodes. This is the most trivial possiblebusiness process: there is one task to be performed, and when that task is complete, the businessprocess ends.

The first JavaBean handles the login screen login.jsp. Its job is just to initialize the jBPM actor idusing the actor component. (In a real application, it would also need to authenticate the user.)

@Name("login")public class Login { @In private Actor actor; private String user;

public String getUser() { return user; }

Seam 2 Reference Guide

32

Page 38: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Here we see the use of @In to inject the built-in Actor component.

The JSP itself is trivial:

The second JavaBean is responsible for starting business process instances, and ending tasks.

public void setUser(String user) { this.user = user; } public String login() { actor.setId(user); return "/todo.jsp"; }}

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%><html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <f:view> <h:form> <div> <h:inputText value="#{login.user}"/> <h:commandButton value="Login" action="#{login.login}"/> </div> </h:form> </f:view> </body></html>

@Name("todoList")public class TodoList { private String description; public String getDescription() { return description; }

public void setDescription(String description) { this.description = description; } @CreateProcess(definition="todo") public void createTodo() {} @StartTask @EndTask

CHAPTER 1. SEAM TUTORIAL

33

Page 39: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The description property accepts user input form the JSP page, and exposes it to the processdefinition, allowing the task description to be set.

The Seam @CreateProcess annotation creates a new jBPM process instance for the named processdefinition.

The Seam @StartTask annotation starts work on a task. The @EndTask ends the task, and allows thebusiness process execution to resume.

In a more realistic example, @StartTask and @EndTask would not appear on the same method,because there is usually work to be done using the application in order to complete the task.

Finally, the meat of the application is in todo.jsp:

public void done() {}

}

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@ taglib uri="http://jboss.com/products/seam/taglib" prefix="s" %><html> <head> <title>Todo List</title> </head> <body> <h1>Todo List</h1> <f:view> <h:form id="list"> <div> <h:outputText value="There are no todo items." rendered="#{empty taskInstanceList}"/> <h:dataTable value="#{taskInstanceList}" var="task" rendered="#{not empty taskInstanceList}"> <h:column> <f:facet name="header"> <h:outputText value="Description"/> </f:facet> <h:inputText value="#{task.description}"/> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Created"/> </f:facet> <h:outputText value="#{task.taskMgmtInstance.processInstance.start}"> <f:convertDateTime type="date"/> </h:outputText> </h:column> <h:column> <f:facet name="header"> <h:outputText value="Priority"/> </f:facet> <h:inputText value="#{task.priority}" style="width: 30"/> </h:column> <h:column> <f:facet name="header">

Seam 2 Reference Guide

34

Page 40: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Let's take this one piece at a time.

The page renders a list of tasks, which it gets from a built-in Seam component named taskInstanceList. The list is defined inside a JSF form.

Each element of the list is an instance of the jBPM class TaskInstance. The following code simplydisplays the interesting properties of each task in the list. For the description, priority and due date, weuse input controls, to allow the user to update these values.

<h:outputText value="Due Date"/> </f:facet> <h:inputText value="#{task.dueDate}" style="width: 100"> <f:convertDateTime type="date" dateStyle="short"/> </h:inputText> </h:column> <h:column> <s:button value="Done" action="#{todoList.done}" taskInstance="#{task}"/> </h:column> </h:dataTable> </div> <div> <h:messages/> </div> <div> <h:commandButton value="Update Items" action="update"/> </div> </h:form> <h:form id="new"> <div> <h:inputText value="#{todoList.description}"/> <h:commandButton value="Create New Item" action="#{todoList.createTodo}"/> </div> </h:form> </f:view> </body></html>

<h:form id="list"><div> <h:outputText value="There are no todo items." rendered="#{empty taskInstanceList}"/> <h:dataTable value="#{taskInstanceList}" var="task" rendered="#{not empty taskInstanceList}"> ... </h:dataTable></div></h:form>

<h:column> <f:facet name="header"> <h:outputText value="Description"/> </f:facet> <h:inputText value="#{task.description}"/>

CHAPTER 1. SEAM TUTORIAL

35

Page 41: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This button ends the task by calling the action method annotated @StartTask @EndTask. It passesthe task id to Seam as a request parameter:

(Note that this is using a Seam <s:button> JSF control from the seam-ui.jar package.)

This button is used to update the properties of the tasks. When the form is submitted, Seam and jBPMwill make any changes to the tasks persistent. There is no need for any action listener method:

A second form on the page is used to create new items, by calling the action method annotated @CreateProcess.

There are several other files needed for the example, but they are just standard jBPM and Seamconfiguration and not very interesting.

1.5. SEAM PAGEFLOW: THE NUMBERGUESS EXAMPLE

</h:column><h:column> <f:facet name="header"> <h:outputText value="Created"/> </f:facet> <h:outputText value="#{task.taskMgmtInstance.processInstance.start}"> <f:convertDateTime type="date"/> </h:outputText></h:column><h:column> <f:facet name="header"> <h:outputText value="Priority"/> </f:facet> <h:inputText value="#{task.priority}" style="width: 30"/></h:column><h:column> <f:facet name="header"> <h:outputText value="Due Date"/> </f:facet> <h:inputText value="#{task.dueDate}" style="width: 100"> <f:convertDateTime type="date" dateStyle="short"/> </h:inputText></h:column>

<h:column> <s:button value="Done" action="#{todoList.done}" taskInstance="#{task}"/></h:column>

<h:commandButton value="Update Items" action="update"/>

<h:form id="new"> <div> <h:inputText value="#{todoList.description}"/> <h:commandButton value="Create New Item" action="#{todoList.createTodo}"/> </div></h:form>

Seam 2 Reference Guide

36

Page 42: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

For Seam applications with relatively freeform (ad hoc) navigation, JSF/Seam navigation rules are aperfectly good way to define the page flow. For applications with a more constrained style ofnavigation, especially for user interfaces which are more stateful, navigation rules make it difficult toreally understand the flow of the system. To understand the flow, you need to piece it together fromthe view pages, the actions and the navigation rules.

Seam allows you to use a jPDL process definition to define pageflow. The simple number guessingexample shows how this is done.

1.5.1. Understanding the code

The example is implemented using one JavaBean, three JSP pages and a jPDL pageflow definition.Let's begin with the pageflow:

<pageflow-definition xmlns="http://jboss.com/products/seam/pageflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.com/products/seam/pageflow http://jboss.com/products/seam/pageflow-2.1.xsd" name="numberGuess"> <start-page name="displayGuess" view-id="/numberGuess.jspx"> <redirect/> <transition name="guess" to="evaluateGuess"> <action expression="#{numberGuess.guess}"/> </transition> <transition name="giveup" to="giveup"/> </start-page> <decision name="evaluateGuess" expression="#{numberGuess.correctGuess}"> <transition name="true" to="win"/> <transition name="false" to="evaluateRemainingGuesses"/> </decision> <decision name="evaluateRemainingGuesses" expression="#{numberGuess.lastGuess}"> <transition name="true" to="lose"/> <transition name="false" to="displayGuess"/> </decision>

CHAPTER 1. SEAM TUTORIAL

37

Page 43: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<page name="giveup" view-id="/giveup.jspx"> <redirect/> <transition name="yes" to="lose"/> <transition name="no" to="displayGuess"/> </page> <page name="win" view-id="/win.jspx"> <redirect/> <end-conversation/> </page> <page name="lose" view-id="/lose.jspx"> <redirect/> <end-conversation/> </page> </pageflow-definition>

The <page> element defines a wait state where the system displays a particular JSF view and waits foruser input. The view-id is the same JSF view id used in plain JSF navigation rules. The redirectattribute tells Seam to use post-then-redirect when navigating to the page. (This results in friendlybrowser URLs.)

The <transition> element names a JSF outcome. The transition is triggered when a JSF actionresults in that outcome. Execution will then proceed to the next node of the pageflow graph, afterinvocation of any jBPM transition actions.

A transition <action> is just like a JSF action, except that it occurs when a jBPM transition occurs.The transition action can invoke any Seam component.

A <decision> node branches the pageflow, and determines the next node to execute by evaluating aJSF EL expression.

Here is what the pageflow looks like in the JBoss Developer Studio pageflow editor:

Seam 2 Reference Guide

38

Page 44: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Now that we have seen the pageflow, it is very, very easy to understand the rest of the application!

Here is the main page of the application, numberGuess.jspx:

<?xml version="1.0"?><jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:s="http://jboss.com/products/seam/taglib" xmlns="http://www.w3.org/1999/xhtml" version="2.0"><jsp:output doctype-root-element="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/><jsp:directive.page contentType="text/html"/><html> <head> <title>Guess a number...</title> <link href="niceforms.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript" src="niceforms.js" /> </head> <body> <h1>Guess a number...</h1> <f:view> <h:form styleClass="niceform"> <div> <h:messages globalOnly="true"/> <h:outputText value="Higher!" rendered="#{numberGuess.randomNumber gt numberGuess.currentGuess}"/> <h:outputText value="Lower!" rendered="#{numberGuess.randomNumber lt numberGuess.currentGuess}"/> </div> <div> I'm thinking of a number between <h:outputText value="#{numberGuess.smallest}"/> and <h:outputText value="#{numberGuess.biggest}"/>. You have <h:outputText value="#{numberGuess.remainingGuesses}"/> guesses. </div> <div> Your guess: <h:inputText value="#{numberGuess.currentGuess}" id="inputGuess" required="true" size="3" rendered="#{(numberGuess.biggest-numberGuess.smallest) gt 20}"> <f:validateLongRange maximum="#{numberGuess.biggest}" minimum="#{numberGuess.smallest}"/> </h:inputText> <h:selectOneMenu value="#{numberGuess.currentGuess}" id="selectGuessMenu" required="true" rendered="#{(numberGuess.biggest-numberGuess.smallest) le 20 and (numberGuess.biggest-numberGuess.smallest) gt 4}">

CHAPTER 1. SEAM TUTORIAL

39

Page 45: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Notice how the command button names the guess transition instead of calling an action directly.

The win.jspx page is predictable:

<s:selectItems value="#{numberGuess.possibilities}" var="i" label="#{i}"/> </h:selectOneMenu> <h:selectOneRadio value="#{numberGuess.currentGuess}" id="selectGuessRadio" required="true" rendered="#{(numberGuess.biggest-numberGuess.smallest) le 4}"> <s:selectItems value="#{numberGuess.possibilities}" var="i" label="#{i}"/> </h:selectOneRadio> <h:commandButton value="Guess" action="guess"/> <s:button value="Cheat" view="/confirm.jspx"/> <s:button value="Give up" action="giveup"/> </div> <div> <h:message for="inputGuess" style="color: red"/> </div> </h:form> </f:view> </body></html></jsp:root>

<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns="http://www.w3.org/1999/xhtml" version="2.0"> <jsp:output doctype-root-element="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3c.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/> <jsp:directive.page contentType="text/html"/> <html> <head> <title>You won!</title> <link href="niceforms.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>You won!</h1> <f:view> Yes, the answer was <h:outputText value="#{numberGuess.currentGuess}" />. It took you <h:outputText value="#{numberGuess.guessCount}" /> guesses. <h:outputText value="But you cheated, so it doesn't count!" rendered="#{numberGuess.cheat}"/> Would you like to <a href="numberGuess.seam">play again</a>? </f:view>

Seam 2 Reference Guide

40

Page 46: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

As is lose.jspx (which I can't be bothered copy/pasting). Finally, the JavaBean Seam component:

</body> </html> </jsp:root>

@Name("numberGuess")@Scope(ScopeType.CONVERSATION)public class NumberGuess implements Serializable { private int randomNumber; private Integer currentGuess; private int biggest; private int smallest; private int guessCount; private int maxGuesses; private boolean cheated;

@Create public void begin() { randomNumber = new Random().nextInt(100); guessCount = 0; biggest = 100; smallest = 1; } public void setCurrentGuess(Integer guess) { this.currentGuess = guess; } public Integer getCurrentGuess() { return currentGuess; } public void guess() { if (currentGuess>randomNumber) { biggest = currentGuess - 1; } if (currentGuess<randomNumber) { smallest = currentGuess + 1; } guessCount ++; } public boolean isCorrectGuess() { return currentGuess==randomNumber; }

CHAPTER 1. SEAM TUTORIAL

41

Page 47: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

public int getBiggest() { return biggest; } public int getSmallest() { return smallest; } public int getGuessCount() { return guessCount; } public boolean isLastGuess() { return guessCount==maxGuesses; }

public int getRemainingGuesses() { return maxGuesses-guessCount; }

public void setMaxGuesses(int maxGuesses) { this.maxGuesses = maxGuesses; }

public int getMaxGuesses() { return maxGuesses; }

public int getRandomNumber() { return randomNumber; }

public void cheated() { cheated = true; } public boolean isCheat() { return cheated; } public List<Integer> getPossibilities() { List<Integer> result = new ArrayList<Integer>(); for(int i=smallest; i<=biggest; i++) result.add(i); return result; } }

Seam 2 Reference Guide

42

Page 48: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The first time a JSP page asks for a numberGuess component, Seam will create a new one for it, andthe @Create method will be invoked, allowing the component to initialize itself.

The pages.xml file starts a Seam conversation (much more about that later), and specifies thepageflow definition to use for the conversation's page flow.

As you can see, this Seam component is pure business logic! It doesn't need to know anything at allabout the user interaction flow. This makes the component potentially more reuseable.

1.6. A COMPLETE SEAM APPLICATION: THE HOTEL BOOKINGEXAMPLE

1.6.1. Introduction

The booking application is a complete hotel room reservation system incorporating the followingfeatures:

User registration

Login

Logout

Set password

Hotel search

Hotel selection

Room reservation

Reservation confirmation

Existing reservation list

<?xml version="1.0" encoding="UTF-8"?><pages xmlns="http://jboss.com/products/seam/pages" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.com/products/seam/pages http://jboss.com/products/seam/pages-2.1.xsd">

<page view-id="/numberGuess.jspx"> <begin-conversation join="true" pageflow="numberGuess"/></page>

<page view-id="/confirm.jspx"> <begin-conversation nested="true" pageflow="cheat"/></page>

</pages>

CHAPTER 1. SEAM TUTORIAL

43

Page 49: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Figure 1.1. Booking example

The booking application uses JSF, EJB 3.0 and Seam, together with Facelets for the view. There is alsoa port of this application to JSF, Facelets, Seam, JavaBeans and Hibernate3.

One of the things you'll notice if you play with this application for long enough is that it is extremelyrobust. You can play with back buttons and browser refresh and opening multiple windows and enteringnonsensical data as much as you like and you will find it very difficult to make the application crash.You might think that we spent weeks testing and fixing bugs to achieve this. Actually, this is not thecase. Seam was designed to make it very straightforward to build robust web applications and a lot ofrobustness that you are probably used to having to code yourself comes naturally and automaticallywith Seam.

As you browse the sourcecode of the example application, and learn how the application works,observe how the declarative state management and integrated validation has been used to achievethis robustness.

1.6.2. Overview of the booking example

Seam 2 Reference Guide

44

Page 50: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The project structure is identical to the previous one, to install and deploy this application, please referto Section 1.1, “Try the examples” . Once you've successfully started the application, you can access itby pointing your browser to http://localhost:8080/seam-booking/

Just nine classes (plus six session beans local interfaces) where used to implement this application. Sixsession bean action listeners contain all the business logic for the listed features.

BookingListAction retrieves existing bookings for the currently logged in user.

ChangePasswordAction updates the password of the currently logged in user.

HotelBookingAction implements the core functionality of the application: hotel roomsearching, selection, booking and booking confirmation. This functionality is implemented as aconversation, so this is the most interesting class in the application.

RegisterAction registers a new system user.

Three entity beans implement the application's persistent domain model.

Hotel is an entity bean that represent a hotel

Booking is an entity bean that represents an existing booking

User is an entity bean to represents a user who can make hotel bookings

1.6.3. Understanding Seam conversations

We encourage you browse the sourcecode at your pleasure. In this tutorial we'll concentrate upon oneparticular piece of functionality: hotel search, selection, booking and confirmation. From the point ofview of the user, everything from selecting a hotel to confirming a booking is one continuous unit ofwork, a conversation. Searching, however, is not part of the conversation. The user can select multiplehotels from the same search results page, in different browser tabs.

Most web application architectures have no first class construct to represent a conversation. Thiscauses enormous problems managing state associated with the conversation. Usually, Java webapplications use a combination of two techniques: first, some state is thrown into the HttpSession;second, persistable state is flushed to the database after every request, and reconstructed from thedatabase at the beginning of each new request.

Since the database is the least scalable tier, this often results in an utterly unacceptable lack ofscalability. Added latency is also a problem, due to the extra traffic to and from the database on everyrequest. To reduce this redundant traffic, Java applications often introduce a data (second-level) cachethat keeps commonly accessed data between requests. This cache is necessarily inefficient, becauseinvalidation is based upon an LRU policy instead of being based upon when the user has finishedworking with the data. Furthermore, because the cache is shared between many concurrenttransactions, we've introduced a whole raft of problem's associated with keeping the cached stateconsistent with the database.

Now consider the state held in the HttpSession. By very careful programming, we might be able tocontrol the size of the session data. This is a lot more difficult than it sounds, since web browserspermit ad hoc non-linear navigation. But suppose we suddenly discover a system requirement thatsays that a user is allowed to have mutiple concurrent conversations, halfway through the developmentof the system (this has happened to me). Developing mechanisms to isolate session state associatedwith different concurrent conversations, and incorporating failsafes to ensure that conversation state

CHAPTER 1. SEAM TUTORIAL

45

Page 51: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

is destroyed when the user aborts one of the conversations by closing a browser window or tab is notfor the faint hearted (I've implemented this stuff twice so far, once for a client application, once forSeam, but I'm famously psychotic).

Now there is a better way.

Seam introduces the conversation context as a first class construct. You can safely keep conversationalstate in this context, and be assured that it will have a well-defined lifecycle. Even better, you won'tneed to be continually pushing data back and forth between the application server and the database,since the conversation context is a natural cache of data that the user is currently working with.

Usually, the components we keep in the conversation context are stateful session beans. (We can alsokeep entity beans and JavaBeans in the conversation context.) There is an ancient canard in the Javacommunity that stateful session beans are a scalability killer. This may have been true in 1998 whenWebFoobar 1.0 was released. It is no longer true today. Application servers like JBoss AS haveextremely sophisticated mechanisms for stateful session bean state replication. (For example, theJBoss EJB3 container performs fine-grained replication, replicating only those bean attribute valueswhich actually changed.) Note that all the traditional technical arguments for why stateful beans areinefficient apply equally to the HttpSession, so the practice of shifting state from business tierstateful session bean components to the web session to try and improve performance is unbelievablymisguided. It is certainly possible to write unscalable applications using stateful session beans, by usingstateful beans incorrectly, or by using them for the wrong thing. But that doesn't mean you shouldnever use them. Anyway, Seam guides you toward a safe usage model. Welcome to 2005.

OK, I'll stop ranting now, and get back to the tutorial.

The booking example application shows how stateful components with different scopes cancollaborate together to achieve complex behaviors. The main page of the booking application allowsthe user to search for hotels. The search results are kept in the Seam session scope. When the usernavigates to one of these hotels, a conversation begins, and a conversation scoped component callsback to the session scoped component to retrieve the selected hotel.

The booking example also demonstrates the use of RichFaces Ajax to implement rich client behaviorwithout the use of handwritten JavaScript.

The search functionality is implemented using a session-scope stateful session bean, similar to the onewe saw in the message list example above.

@Stateful@Name("hotelSearch")@Scope(ScopeType.SESSION)@Restrict("#{identity.loggedIn}")public class HotelSearchingAction implements HotelSearching{ @PersistenceContext private EntityManager em; private String searchString; private int pageSize = 10; private int page; @DataModel private List<Hotel> hotels; public void find()

Seam 2 Reference Guide

46

Page 52: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

{ page = 0; queryHotels(); } public void nextPage() { page++; queryHotels(); } private void queryHotels() { hotels = em.createQuery("select h from Hotel h where lower(h.name) like #{pattern} " + "or lower(h.city) like #{pattern} " + "or lower(h.zip) like #{pattern} " + "or lower(h.address) like #{pattern}") .setMaxResults(pageSize) .setFirstResult( page * pageSize ) .getResultList(); } public boolean isNextPageAvailable() { return hotels!=null && hotels.size()==pageSize; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } @Factory(value="pattern", scope=ScopeType.EVENT) public String getSearchPattern() { return searchString==null ? "%" : '%' + searchString.toLowerCase().replace('*', '%') + '%'; } public String getSearchString() { return searchString; } public void setSearchString(String searchString) { this.searchString = searchString; }

CHAPTER 1. SEAM TUTORIAL

47

Page 53: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The EJB standard @Stateful annotation identifies this class as a stateful session bean. Statefulsession beans are scoped to the conversation context by default.

The @Restrict annotation applies a security restriction to the component. It restricts access to thecomponent allowing only logged-in users. The security chapter explains more about security in Seam.

The @DataModel annotation exposes a List as a JSF ListDataModel. This makes it easy toimplement clickable lists for search screens. In this case, the list of hotels is exposed to the page as a ListDataModel in the conversation variable named hotels.

The EJB standard @Remove annotation specifies that a stateful session bean should be removed andits state destroyed after invocation of the annotated method. In Seam, all stateful session beans mustdefine a method with no parameters marked @Remove. This method will be called when Seam destroysthe session context.

The main page of the application is a Facelets page. Let's look at the fragment which relates tosearching for hotels:

@Remove public void destroy() {}}

<div class="section"> <span class="errors"> <h:messages globalOnly="true"/></span> <h1>Search Hotels</h1>

<h:form id="searchCriteria"><fieldset> <h:inputText id="searchString" value="#{hotelSearch.searchString}" style="width: 165px;"> <a:support event="onkeyup" actionListener="#{hotelSearch.find}" reRender="searchResults" /> </h:inputText> <a:commandButton id="findHotels" value="Find Hotels" action="#{hotelSearch.find}" reRender="searchResults"/> <a:status> <f:facet name="start"> <h:graphicImage value="/img/spinner.gif"/> </f:facet> </a:status> <br/> <h:outputLabel for="pageSize">Maximum results:</h:outputLabel> <h:selectOneMenu value="#{hotelSearch.pageSize}" id="pageSize"> <f:selectItem itemLabel="5" itemValue="5"/> <f:selectItem itemLabel="10" itemValue="10"/> <f:selectItem itemLabel="20" itemValue="20"/> </h:selectOneMenu> </fieldset> </h:form>

Seam 2 Reference Guide

48

Page 54: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The RichFaces Ajax <a:support> tag allows a JSF action event listener to be called by asynchronousXMLHttpRequest when a JavaScript event like onkeyup occurs. Even better, the reRender attributelets us render a fragment of the JSF page and perform a partial page update when the asynchronousresponse is received.

The RichFaces Ajax <a:status> tag lets us display a cheesy animated image while we wait forasynchronous requests to return.

The RichFaces Ajax <a:outputPanel> tag defines a region of the page which can be re-rendered byan asynchronous request.

The Seam <s:link> tag lets us attach a JSF action listener to an ordinary (non-JavaScript) HTMLlink. The advantage of this over the standard JSF <h:commandLink> is that it preserves the operationof "open in new window" and "open in new tab". Also notice that we use a method binding with aparameter: #{hotelBooking.selectHotel(hot)}. This is not possible in the standard Unified EL,but Seam provides an extension to the EL that lets you use parameters on any method bindingexpression.

If you're wondering how navigation occurs, you can find all the rules in WEB-INF/pages.xml; this isdiscussed in the navigation section of this book.

</div>

<a:outputPanel id="searchResults"> <div class="section"> <h:outputText value="No Hotels Found" rendered="#{hotels != null and hotels.rowCount==0}"/> <h:dataTable id="hotels" value="#{hotels}" var="hot" rendered="#{hotels.rowCount>0}"> <h:column> <f:facet name="header">Name</f:facet> #{hot.name} </h:column> <h:column> <f:facet name="header">Address</f:facet> #{hot.address} </h:column> <h:column> <f:facet name="header">City, State</f:facet> #{hot.city}, #{hot.state}, #{hot.country} </h:column> <h:column> <f:facet name="header">Zip</f:facet> #{hot.zip} </h:column> <h:column> <f:facet name="header">Action</f:facet> <s:link id="viewHotel" value="View Hotel" action="#{hotelBooking.selectHotel(hot)}"/> </h:column> </h:dataTable> <s:link value="More results" action="#{hotelSearch.nextPage}" rendered="#{hotelSearch.nextPageAvailable}"/> </div></a:outputPanel>

CHAPTER 1. SEAM TUTORIAL

49

Page 55: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This page displays the search results dynamically as we type, and lets us choose a hotel and pass it tothe selectHotel() method of the HotelBookingAction, which is where the really interesting stuffis going to happen.

Now let's see how the booking example application uses a conversation-scoped stateful session beanto achieve a natural cache of persistent data related to the conversation. The following code exampleis pretty long. But if you think of it as a list of scripted actions that implement the various steps of theconversation, it's understandable. Read the class from top to bottom, as if it were a story.

@Stateful@Name("hotelBooking")@Restrict("#{identity.loggedIn}")public class HotelBookingAction implements HotelBooking{ @PersistenceContext(type=EXTENDED) private EntityManager em; @In private User user; @In(required=false) @Out private Hotel hotel; @In(required=false) @Out(required=false) private Booking booking; @In private FacesMessages facesMessages; @In private Events events; @Logger private Log log; private boolean bookingValid; @Begin public void selectHotel(Hotel selectedHotel) { hotel = em.merge(selectedHotel); } public void bookHotel() { booking = new Booking(hotel, user); Calendar calendar = Calendar.getInstance(); booking.setCheckinDate( calendar.getTime() ); calendar.add(Calendar.DAY_OF_MONTH, 1); booking.setCheckoutDate( calendar.getTime() ); } public void setBookingDetails() {

Seam 2 Reference Guide

50

Page 56: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This bean uses an EJB3 extended persistence context, so that any entity instances remain managed forthe whole lifecycle of the stateful session bean.

The @Out annotation declares that an attribute value is passed to a context variable after methodinvocations. In this case, the context variable named hotel will be set to the value of the hotelinstance variable after every action listener invocation completes.

The @Begin annotation specifies that the annotated method begins a long-running conversation, so thecurrent conversation context will not be destroyed at the end of the request. Instead, it will be re-associated with every request from the current window, and destroyed either by timeout due toconversation inactivity or invocation of a matching @End method.

Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -1); if ( booking.getCheckinDate().before( calendar.getTime() ) ) { facesMessages.addToControl("checkinDate", "Check in date must be a future date"); bookingValid=false; } else if ( !booking.getCheckinDate().before( booking.getCheckoutDate() ) ) { facesMessages.addToControl("checkoutDate", "Check out date must be later than check in date"); bookingValid=false; } else { bookingValid=true; } } public boolean isBookingValid() { return bookingValid; } @End public void confirm() { em.persist(booking); facesMessages.add("Thank you, #{user.name}, your confirmation number " + " for #{hotel.name} is #{booki g.id}"); log.info("New booking: #{booking.id} for #{user.username}"); events.raiseTransactionSuccessEvent("bookingConfirmed"); } @End public void cancel() {} @Remove public void destroy() {}

CHAPTER 1. SEAM TUTORIAL

51

Page 57: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The @End annotation specifies that the annotated method ends the current long-running conversation,so the current conversation context will be destroyed at the end of the request.

This EJB remove method will be called when Seam destroys the conversation context. Don't forget todefine this method!

HotelBookingAction contains all the action listener methods that implement selection, booking andbooking confirmation, and holds state related to this work in its instance variables. We think you'llagree that this code is much cleaner and simpler than getting and setting HttpSession attributes.

Even better, a user can have multiple isolated conversations per login session. Try it! Log in, run asearch, and navigate to different hotel pages in multiple browser tabs. You'll be able to work oncreating two different hotel reservations at the same time. If you leave any one conversation inactivefor long enough, Seam will eventually time out that conversation and destroy its state. If, after ending aconversation, you backbutton to a page of that conversation and try to perform an action, Seam willdetect that the conversation was already ended, and redirect you to the search page.

1.6.4. The Seam UI control library

If you check inside the WAR file for the booking application, you'll find seam-ui.jar in the WEB-INF/lib directory. This package contains a number of JSF custom controls that integrate with Seam.The booking application uses the <s:link> control for navigation from the search screen to the hotelpage:

The use of <s:link> here allows us to attach an action listener to a HTML link without breaking thebrowser's "open in new window" feature. The standard JSF <h:commandLink> does not work with"open in new window". We'll see later that <s:link> also offers a number of other useful features,including conversation propagation rules.

The booking application uses some other Seam and RichFaces Ajax controls, especially on the /book.xhtml page. We won't get into the details of those controls here, but if you want to understandthis code, please refer to the chapter covering Seam's functionality for JSF form validation.

1.6.5. The Seam Debug Page

The WAR also includes seam-debug.jar. The Seam debug page will be available if this jar is deployedin WEB-INF/lib, along with the Facelets, and if you set the debug property of the init component:

This page lets you browse and inspect the Seam components in any of the Seam contexts associatedwith your current login session. Just point your browser at http://localhost:8080/seam-booking/debug.seam .

<s:link value="View Hotel" action="#{hotelBooking.selectHotel(hot)}"/>

<core:init jndi-pattern="@jndiPattern@" debug="true"/>

Seam 2 Reference Guide

52

Page 58: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.7. A COMPLETE APPLICATION FEATURING SEAM AND JBPM: THEDVD STORE EXAMPLE

The DVD Store demo application shows the practical usage of jBPM for both task management andpageflow.

The user screens take advantage of a jPDL pageflow to implement searching and shopping cartfunctionality.

CHAPTER 1. SEAM TUTORIAL

53

Page 59: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Figure 1.2. DVD Store example

The administration screens take use jBPM to manage the approval and shipping cycle for orders. Thebusiness process may even be changed dynamically, by selecting a different process definition!

Seam 2 Reference Guide

54

Page 60: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Figure 1.3. DVD Store example

1.8. AN EXAMPLE OF SEAM WITH HIBERNATE: THE HIBERNATEBOOKING EXAMPLE

The Hibernate Booking demo is a straight port of the Booking demo to an alternative architecture thatuses Hibernate for persistence and JavaBeans instead of session beans.

TODO

Look in the hibernate directory.

1.9. A RESTFUL SEAM APPLICATION: THE BLOG EXAMPLE

Seam makes it very easy to implement applications which keep state on the server-side. However,server-side state is not always appropriate, especially in for functionality that serves up content. Forthis kind of problem we often need to let the user bookmark pages and have a relatively statelessserver, so that any page can be accessed at any time, via the bookmark. The Blog example shows howto a implement RESTful application using Seam. Every page of the application can be bookmarked,including the search results page.

CHAPTER 1. SEAM TUTORIAL

55

Page 61: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Figure 1.4. Blog example

The Blog example demonstrates the use of "pull"-style MVC, where instead of using action listenermethods to retrieve data and prepare the data for the view, the view pulls data from components as itis being rendered.

1.9.1. Using "pull"-style MVC

This snippet from the index.xhtml facelets page displays a list of recent blog entries:

<h:dataTable value="#{blog.recentBlogEntries}" var="blogEntry" rows="3"><h:column><div class="blogEntry"><h3>#{blogEntry.title}</h3><div> <h:outputText escape="false" value="#{blogEntry.excerpt==null ? blogEntry.body : blogEntry.excerpt}"/></div><p> <h:outputLink value="entry.seam" rendered="#{blogEntry.excerpt!=null}"> <f:param name="blogEntryId" value="#{blogEntry.id}"/> Read more... </h:outputLink></p><p>[Posted on <h:outputText value="#{blogEntry.date}"> <f:convertDateTime timeZone="#{blog.timeZone}"

Seam 2 Reference Guide

56

Page 62: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If we navigate to this page from a bookmark, how does the data used by the <h:dataTable> actuallyget initialized? Well, what happens is that the Blog is retrieved lazily—"pulled"—when needed, by aSeam component named blog. This is the opposite flow of control to what is usual in traditional webaction-based frameworks like Struts.

This component uses a seam-managed persistence context. Unlike the other examples we've seen, thispersistence context is managed by Seam, instead of by the EJB3 container. The persistence contextspans the entire web request, allowing us to avoid any exceptions that occur when accessingunfetched associations in the view.

The @Unwrap annotation tells Seam to provide the return value of the method—the Blog—instead of theactual BlogService component to clients. This is the Seam manager component pattern.

This is good so far, but what about bookmarking the result of form submissions, such as a searchresults page?

1.9.2. Bookmarkable search results page

The blog example has a tiny form in the top right of each page that allows the user to search for blogentries. This is defined in a file, menu.xhtml, included by the facelets template, template.xhtml:

locale="#{blog.locale}" type="both"/></h:outputText>] <h:outputLink value="entry.seam">[Link] <f:param name="blogEntryId" value="#{blogEntry.id}"/></h:outputLink></p></div></h:column></h:dataTable>

@Name("blog")@Scope(ScopeType.STATELESS)@AutoCreatepublic class BlogService { @In EntityManager entityManager; @Unwrap public Blog getBlog() { return (Blog) entityManager.createQuery("select distinct b from Blog b left join fetch b.blogEntries") .setHint("org.hibernate.cacheable", true) .getSingleResult(); }

<div id="search"> <h:form> <h:inputText value="#{searchAction.searchPattern}"/>

CHAPTER 1. SEAM TUTORIAL

57

Page 63: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

To implement a bookmarkable search results page, we need to perform a browser redirect afterprocessing the search form submission. Because we used the JSF view id as the action outcome, Seamautomatically redirects to the view id when the form is submitted. Alternatively, we could have defineda navigation rule like this:

Then the form would have looked like this:

But when we redirect, we need to include the values submitted with the form as request parameters,to get a bookmarkable URL like http://localhost:8080/seam-blog/search.seam?searchPattern=seam. JSF does not provide an easy way to do this, but Seam does. We use a Seampage parameter, defined in WEB-INF/pages.xml:

This tells Seam to include the value of #{searchService.searchPattern} as a request parameternamed searchPattern when redirecting to the page, and then re-apply the value of that parameterto the model before rendering the page.

The redirect takes us to the search.xhtml page:

<h:commandButton value="Search" action="/search.xhtml"/> </h:form></div>

<navigation-rule> <navigation-case> <from-outcome>searchResults</from-outcome> <to-view-id>/search.xhtml</to-view-id> <redirect/> </navigation-case></navigation-rule>

<div id="search"> <h:form> <h:inputText value="#{searchAction.searchPattern}"/> <h:commandButton value="Search" action="searchResults"/> </h:form></div>

<pages> <page view-id="/search.xhtml"> <param name="searchPattern" value="#{searchService.searchPattern}"/> </page></pages>

<h:dataTable value="#{searchResults}" var="blogEntry"> <h:column> <div> <h:outputLink value="entry.seam"> <f:param name="blogEntryId" value="#{blogEntry.id}"/> #{blogEntry.title} </h:outputLink> posted on <h:outputText value="#{blogEntry.date}"> <f:convertDateTime timeZone="#{blog.timeZone}" locale="#{blog.locale}" type="both"/>

Seam 2 Reference Guide

58

Page 64: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Which again uses "pull"-style MVC to retrieve the actual search results:

</h:outputText> </div> </h:column></h:dataTable>

@Name("searchService")public class SearchService { @In private EntityManager entityManager; private String searchPattern; @Factory("searchResults") public List<BlogEntry> getSearchResults() { if (searchPattern==null) { return null; } else { return entityManager.createQuery("select be from BlogEntry be "" + "where lower(be.title) like :searchPattern " + "lower(be.body) like :searchPattern order by be.date desc") .setParameter( "searchPattern", getSqlSearchPattern() ) .setMaxResults(100) .getResultList(); } }

private String getSqlSearchPattern() { return searchPattern==null ? "" : '%' + searchPattern.toLowerCase().replace('*', '%').replace('?', '_') + '%'; }

public String getSearchPattern() { return searchPattern; }

public void setSearchPattern(String searchPattern) { this.searchPattern = searchPattern; }

}

CHAPTER 1. SEAM TUTORIAL

59

Page 65: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

1.9.3. Using "push"-style MVC in a RESTful application

Very occasionally, it makes more sense to use push-style MVC for processing RESTful pages, and soSeam provides the notion of a page action. The Blog example uses a page action for the blog entry page,entry.xhtml. Note that this is a little bit contrived, it would have been easier to use pull-style MVChere as well.

The entryAction component works much like an action class in a traditional push-MVC action-oriented framework like Struts:

Page actions are also declared in pages.xml:

Notice that the example is using page actions for some other functionality—the login challenge, and thepageview counter. Also notice the use of a parameter in the page action method binding. This is not astandard feature of JSF EL, but Seam lets you use it, not just for page actions, but also in JSF methodbindings.

When the entry.xhtml page is requested, Seam first binds the page parameter blogEntryId to themodel, then runs the page action, which retrieves the needed data—the blogEntry—and places it in theSeam event context. Finally, the following is rendered:

@Name("entryAction")@Scope(STATELESS)public class EntryAction{ @In(create=true) private Blog blog; @Out private BlogEntry blogEntry; public void loadBlogEntry(String id) throws EntryNotFoundException { blogEntry = blog.getBlogEntry(id); if (blogEntry==null) throw new EntryNotFoundException(id); } }

<pages> <page view-id="/entry.xhtml" action="#{entryAction.loadBlogEntry(blogEntry.id)}"> <param name="blogEntryId" value="#{blogEntry.id}"/> </page> <page view-id="/post.xhtml" action="#{loginAction.challenge}"/> <page view-id="*" action="#{blog.hitCount.hit}"/></pages>

<div class="blogEntry"><h3>#{blogEntry.title}</h3><div> <h:outputText escape="false" value="#{blogEntry.body}"/></div><p> [Posted on

Seam 2 Reference Guide

60

Page 66: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If the blog entry is not found in the database, the EntryNotFoundException exception is thrown. Wewant this exception to result in a 404 error, not a 505, so we annotate the exception class:

An alternative implementation of the example does not use the parameter in the method binding:

It is a matter of taste which implementation you prefer.

<h:outputText value="#{blogEntry.date}"> <f:convertDateTime timezone="#{blog.timeZone}" locale="#{blog.locale}" type="both"/> </h:outputText>]</p></div>

@ApplicationException(rollback=true)@HttpError(errorCode=HttpServletResponse.SC_NOT_FOUND)public class EntryNotFoundException extends Exception{ EntryNotFoundException(String id) { super("entry not found: " + id); }}

@Name("entryAction")@Scope(STATELESS)public class EntryAction{ @In(create=true) private Blog blog; @In @Out private BlogEntry blogEntry; public void loadBlogEntry() throws EntryNotFoundException { blogEntry = blog.getBlogEntry( blogEntry.getId() ); if (blogEntry==null) throw new EntryNotFoundException(id); } }

<pages> <page view-id="/entry.xhtml" action="#{entryAction.loadBlogEntry}"> <param name="blogEntryId" value="#{blogEntry.id}"/> </page></pages>

CHAPTER 1. SEAM TUTORIAL

61

Page 67: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 2. GETTING STARTED WITH SEAM, USING SEAM-GENThe Seam distribution includes a command line utility that makes it really easy to set up an Eclipseproject, generate some simple Seam skeleton code, and reverse engineer an application from apreexisting database.

You can use seam-gen without Eclipse, but in this tutorial, we want to show you how to use it inconjunction with Eclipse for debugging and integration testing. If you don't want to install Eclipse, youcan still follow along with this tutorial and all steps can be performed from the command line.

Seam-gen is basically just a big ugly Ant script wrapped around Hibernate Tools, together with sometemplates. That makes it easy to customize if you need to.

2.1. BEFORE YOU START

Make sure you have JDK 5 or JDK 6, JBoss EAP 4.3 CP04 and Ant 1.6, along with recent versions ofEclipse, the JBoss IDE plugin for Eclipse and the TestNG plugin for Eclipse correctly installed beforestarting. Add your JBoss installation to the JBoss Server View in Eclipse. Start JBoss in debug mode.Finally, start a command prompt in the directory where you unzipped the Seam distribution.

JBoss has sophisticated support for hot re-deployment of WARs and EARs. Unfortunately, due to bugsin the JVM, repeated redeployment of an EAR (common during development) eventually causes theJVM to run out of permanent generation space. For this reason, we recommend running JBoss in aJVM with a large permanent generation space at development time. If you're running JBoss fromJBoss IDE, you can configure this in the server launch configuration, under "VM arguments". Wesuggest the following values:

If you don't have so much memory available, the following is our minimum recommendation:

If you're running JBoss from the command line, you can configure the JVM options in bin/run.conf.

2.2. SETTING UP A NEW ECLIPSE PROJECT

The first thing we need to do is configure seam-gen for your environment: JBoss EnterpriseApplication Platform installation directory, Eclipse workspace, and database connection. It's easy, justtype:

And you will be prompted for the needed information:

-Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512

-Xms256m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=256

cd jboss-seam-2.0.xseam setup

~/workspace/jboss-seam$ ./seam setupBuildfile: build.xml

init:

setup:

Seam 2 Reference Guide

62

Page 68: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

[echo] Welcome to seam-gen :-) [input] Enter your Java project workspace (the directory that contains your Seam projects) [C:/Projects] [C:/Projects]/Users/pmuir/workspace [input] Enter your JBoss home directory [C:/Program Files/jboss-4.2.2.GA] [C:/Program Files/jboss-4.2.2.GA]/Applications/jboss-4.2.2.GA [input] Enter the project name [myproject] [myproject]helloworld [echo] Accepted project name as: helloworld [input] Select a RichFaces skin (not applicable if using ICEFaces) [blueSky] ([blueSky], classic, ruby, wine, deepMarine, emeraldTown, sakura, DEFAULT)

[input] Is this project deployed as an EAR (with EJB components) or a WAR (with no EJB support) [ear] ([ear], war, )

[input] Enter the Java package name for your session beans [com.mydomain.helloworld] [com.mydomain.helloworld]org.jboss.helloworld [input] Enter the Java package name for your entity beans [org.jboss.helloworld] [org.jboss.helloworld]

[input] Enter the Java package name for your test cases [org.jboss.helloworld.test] [org.jboss.helloworld.test]

[input] What kind of database are you using? [hsql] ([hsql], mysql, oracle, postgres, mssql, db2, sybase, enterprisedb, h2)mysql [input] Enter the Hibernate dialect for your database [org.hibernate.dialect.MySQLDialect] [org.hibernate.dialect.MySQLDialect]

[input] Enter the filesystem path to the JDBC driver jar [lib/hsqldb.jar] [lib/hsqldb.jar]/Users/pmuir/java/mysql.jar [input] Enter JDBC driver class for your database [com.mysql.jdbc.Driver] [com.mysql.jdbc.Driver]

[input] Enter the JDBC URL for your database [jdbc:mysql:///test] [jdbc:mysql:///test]jdbc:mysql:///helloworld [input] Enter database username [sa] [sa]pmuir [input] Enter database password [] []

[input] skipping input as property hibernate.default_schema.new has already been set. [input] Enter the database catalog name (it is OK to leave this blank) [] []

[input] Are you working with tables that already exist in the database? [n] (y, [n], )y [input] Do you want to drop and recreate the database tables and data in import.sql each time you deploy? [n] (y, [n], )n

CHAPTER 2. GETTING STARTED WITH SEAM, USING SEAM-GEN

63

Page 69: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The tool provides sensible defaults, which you can accept by just pressing enter at the prompt.

The most important choice you need to make is between EAR deployment and WAR deployment ofyour project. EAR projects support EJB 3.0 and require Java EE 5. WAR projects do not support EJB3.0, but may be deployed to a J2EE environment. The packaging of a WAR is also simpler tounderstand. If you installed an EJB3-ready application server like JBoss, choose EAR. Otherwise,choose WAR. We will assume that you have chosen an EAR deployment for the rest of the tutorial, butyou can follow exactly the same steps for a WAR deployment.

If you are working with an existing data model, make sure you tell seam-gen that the tables alreadyexist in the database.

The settings are stored in seam-gen/build.properties, but you can also modify them simply byrunning seam setup a second time.

Now we can create a new project in our Eclipse workspace directory, by typing:

This copies the Seam jars, dependent jars and the JDBC driver jar to a new Eclipse project, andgenerates all needed resources and configuration files, a facelets template file and stylesheet, alongwith Eclipse metadata and an Ant build script. The Eclipse project will be automatically deployed to anexploded directory structure in the JBoss Enterprise Application Server as soon as you add the projectusing New -> Project... -> General -> Project -> Next, typing the Project name(helloworld in this case), and then clicking Finish. Do not select Java Project from the NewProject wizard.

[input] Enter your ICEfaces home directory (leave blank to omit ICEfaces) [] []

[propertyfile] Creating new property file: /Users/pmuir/workspace/jboss-seam/seam-gen/build.properties [echo] Installing JDBC driver jar to JBoss server [echo] Type 'seam create-project' to create the new project

BUILD SUCCESSFULTotal time: 1 minute 32 seconds~/workspace/jboss-seam $

seam new-project

C:\Projects\jboss-seam>seam new-projectBuildfile: build.xml

...

new-project: [echo] A new Seam project named 'helloworld' was created in the C:\Projects directory [echo] Type 'seam explode' and go to http://localhost:8080/helloworld [echo] Eclipse Users: Add the project into Eclipse using File > New > Project and select General > Project (not Java Project) [echo] NetBeans Users: Open the project in NetBeans

BUILD SUCCESSFULTotal time: 7 secondsC:\Projects\jboss-seam>

Seam 2 Reference Guide

64

Page 70: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If your default JDK in Eclipse is not a Java SE 5 or Java SE 6 JDK, you will need to select a Java SE 5compliant JDK using Project -> Properties -> Java Compiler.

Alternatively, you can deploy the project from outside Eclipse by typing seam explode.

Go to http://localhost:8080/helloworld to see a welcome page. This is a facelets page, view/home.xhtml, using the template view/layout/template.xhtml. You can edit this page, orthe template, in eclipse, and see the results immediately, by clicking refresh in your browser.

The generated XML configuration documetents which appear in the project directory releate to JavaEE. In general cases these files should not have to be viewed and are usually the same between allSeam projects.

The generated project includes three database and persistence configurations. The persistence-test.xml and import-test.sql files are used when running the TestNG unit tests againstHSQLDB. The database schema and the test data in import-test.sql is always exported to thedatabase before running tests. The myproject-dev-ds.xml, persistence-dev.xmland import-dev.sql files are for use when deploying the application to your development database. The schemamight be exported automatically at deployment, depending upon whether seam-gen has beenconfigureed to work with an existing database. The myproject-prod-ds.xml, persistence-prod.xmland import-prod.sql files are for use when deploying the application to your productiondatabase. The schema is not exported automatically at deployment.

2.3. CREATING A NEW ACTION

If you are used to traditional action-style web frameworks, you are probably wondering how you cancreate a simple web page with a stateless action method in Java. If you type:

Seam will prompt for some information, and generate a new facelets page and Seam component foryour project.

seam new-action

C:\Projects\jboss-seam>seam new-actionBuildfile: build.xml

validate-workspace:

validate-project:

action-input: [input] Enter the Seam component nameping [input] Enter the local interface name [Ping]

[input] Enter the bean class name [PingBean]

[input] Enter the action method name [ping]

[input] Enter the page name [ping]

setup-filters:

CHAPTER 2. GETTING STARTED WITH SEAM, USING SEAM-GEN

65

Page 71: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Because we have added a new Seam component, we need to restart the exploded directorydeployment. You can do this by typing seam restart, or by running the restart target in thegenerated project build.xml file from inside Eclipse. Another way to force a restart is to edit the file resources/META-INF/application.xml in Eclipse.

NOTE

JBoss does not require a restart each time the application changes.

Go to http://localhost:8080/helloworld/ping.seam and click the button to see the codebehind this action by looking in the project src directory. Place a breakpoint in the ping() method,and click the button again.

Finally, locate the PingTest.xml file in the test package and run the integration tests using theTestNG plugin for Eclipse. Alternatively, run the tests using seam test or the test target of thegenerated build.

2.4. CREATING A FORM WITH AN ACTION

The next step is to create a form. Type:

new-action: [echo] Creating a new stateless session bean component with an action method [copy] Copying 1 file to C:\Projects\helloworld\src\action\org\jboss\helloworld [copy] Copying 1 file to C:\Projects\helloworld\src\action\org\jboss\helloworld [copy] Copying 1 file to C:\Projects\helloworld\src\action\org\jboss\helloworld\test [copy] Copying 1 file to C:\Projects\helloworld\src\action\org\jboss\helloworld\test [copy] Copying 1 file to C:\Projects\helloworld\view [echo] Type 'seam restart' and go to http://localhost:8080/helloworld/ping.seam

BUILD SUCCESSFULTotal time: 13 secondsC:\Projects\jboss-seam>

seam new-form

C:\Projects\jboss-seam>seam new-formBuildfile: C:\Projects\jboss-seam\seam-gen\build.xml

validate-workspace:

validate-project:

action-input: [input] Enter the Seam component namehello [input] Enter the local interface name [Hello]

Seam 2 Reference Guide

66

Page 72: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Restart the application again, and go to http://localhost:8080/helloworld/hello.seam.Then take a look at the generated code. Run the test. Try adding some new fields to the form and Seamcomponent (remember to restart the deployment each time you change the Java code).

2.5. GENERATING AN APPLICATION FROM AN EXISTING DATABASE

Manually create some tables in your database. (If you need to switch to a different database, run seam setup again.) Now type:

Restart the deployment, and go to http://localhost:8080/helloworld. You can browse thedatabase, edit existing objects, and create new objects. If you look at the generated code, you willprobably be amazed how simple it is. Seam was designed so that data access code is easy to write byhand, even for people who don't want to use seam-gen.

2.6. GENERATING AN APPLICATION FROM EXISTING JPA/EJB3ENTITIES

Place your existing, valid entity classes inside the src/model. Now type

Restart the deployment, and go to http://localhost:8080/helloworld.

2.7. DEPLOYING THE APPLICATION AS AN EAR

Finally, we want to be able to deploy the application using standard Java EE 5 packaging. First, we

[input] Enter the bean class name [HelloBean]

[input] Enter the action method name [hello]

[input] Enter the page name [hello]

setup-filters:

new-form: [echo] Creating a new stateful session bean component with an action method [copy] Copying 1 file to C:\Projects\hello\src\com\hello [copy] Copying 1 file to C:\Projects\hello\src\com\hello [copy] Copying 1 file to C:\Projects\hello\src\com\hello\test [copy] Copying 1 file to C:\Projects\hello\view [copy] Copying 1 file to C:\Projects\hello\src\com\hello\test [echo] Type 'seam restart' and go to http://localhost:8080/hello/hello.seam

BUILD SUCCESSFULTotal time: 5 secondsC:\Projects\jboss-seam>

seam generate-entities

seam generate-ui

CHAPTER 2. GETTING STARTED WITH SEAM, USING SEAM-GEN

67

Page 73: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

need to remove the exploded directory by running seam unexplode. To deploy the EAR, we can type seam deploy at the command prompt, or run the deploy target of the generated project build script.You can undeploy using seam undeploy or the undeploy target.

By default, the application will be deployed with the dev profile. The EAR will include the persistence-dev.xml and import-dev.sql files, and the myproject-dev-ds.xml file will bedeployed. You can change the profile, and use the prod profile, by typing

You can even define new deployment profiles for your application. Just add appropriately named filesto your project—for example, persistence-staging.xml, import-staging.sql and myproject-staging-ds.xml—and select the name of the profile using -Dprofile=staging.

2.8. SEAM AND INCREMENTAL HOT DEPLOYMENT

When you deploy your Seam application as an exploded directory, you will receive support forincremental hot deployment at development time. You need to enable debug mode in both Seam andFacelets, by adding this line to components.xml:

Now, the following files may be redeployed without requiring a full restart of the web application:

any facelets page

any pages.xml file

But if we want to change any Java code, we still need to do a full restart of the application. (In JBossthis may be accomplished by touching the top level deployment descriptor: application.xml for anEAR deployment, or web.xml for a WAR deployment.)

But if you really want a fast edit/compile/test cycle, Seam supports incremental redeployment ofJavaBean components. To make use of this functionality, you must deploy the JavaBean componentsinto the WEB-INF/dev directory, so that they will be loaded by a special Seam classloader, instead ofby the WAR or EAR classloader.

You need to be aware of the following limitations:

the components must be JavaBean components, they cannot be EJB3 beans (we are workingon fixing this limitation)

entities can never be hot-deloyed

components deployed via components.xml may not be hot-deployed

the hot-deployable components will not be visible to any classes deployed outside of WEB-INF/dev

Seam debug mode must be enabled and jboss-seam-debug.jar must be in WEB-INF/lib

You must have the Seam filter installed in web.xml

You may see errors if the system is placed under any load and debug is enabled.

seam -Dprofile=prod deploy

<core:init debug="true">

Seam 2 Reference Guide

68

Page 74: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If you create a WAR project using seam-gen, incremental hot deployment is available out of the box forclasses in the src/action source directory. However, seam-gen does not support incremental hotdeployment for EAR projects.

CHAPTER 2. GETTING STARTED WITH SEAM, USING SEAM-GEN

69

Page 75: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSSTOOLSJBoss Tools is a collection of Eclipse plugins and contains a project creation wizard for Seam, ContentAssist for the Unified Expression Language (EL) in both facelets and Java code, a graphical editor forjPDL, a graphical editor for Seam configuration files, support for running Seam integration tests fromwithin Eclipse, and much more. In short, if you are an Eclipse user, then you'll want JBoss Tools!

JBoss Tools, as with seam-gen, works best with the JBoss Enterprise Application Platform, but it'spossible with a few tweaks to get your app running on other application servers. The changes are muchlike those described for seam-gen later in this reference manual.

3.1. BEFORE YOU START

Make sure you have JBoss EAP 4.3 FP01 and JBDS installed.

3.2. SETTING UP A NEW SEAM PROJECT

Start up Eclipse and select the Seam perspective.

Go to File -> New -> Seam Web Project.

First, enter a name for your new project. For this tutorial, we are going to use helloworld .

Now, we need to tell JBoss Tools about the JBoss Enterprise Application Server. This is a two stageprocess, first we need to define a runtime, make sure you select JBoss AS 4.2:

Seam 2 Reference Guide

70

Page 76: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Enter a name for the runtime, and locate it on your hard drive:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

71

Page 77: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Next, we need to define a server JBoss Tools can deploy the project to. Make sure to again selectJBoss AS 4.2, and also the runtime you just defined:

Seam 2 Reference Guide

72

Page 78: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

On the next screen give the server a name, and hit Finish:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

73

Page 79: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Make sure the runtime and server you just created are selected, select Dynamic Web Project with Seam2.0 (technology preview) and hit Next:

Seam 2 Reference Guide

74

Page 80: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The next 3 screens allow you to further customize your new project, but for us the defaults are fine.Just click Next until you reach the final screen.

The first step here is to tell JBoss Tools about the Seam download you want to use. Add a new SeamRuntime - make sure to give it a name, and select 2.0 as the version:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

75

Page 81: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The most important choice you need to make is between EAR deployment and WAR deployment ofyour project. EAR projects support EJB 3.0 and require Java EE 5. WAR projects do not support EJB3.0, but may be deployed to a J2EE environment. The packaging of a WAR is also simpler tounderstand. If you installed an EJB3-ready application server like JBoss, choose EAR. Otherwise,choose WAR. We'll assume that you've chosen a WAR deployment for the rest of the tutorial, but youcan follow exactly the same steps for a EAR deployment.

Next, select your database type. We'll assume you have MySQL installed, with an existing schema.You'll need to tell JBoss Tools about the database, select MySQL as the database, and create a newconnection profile. Select Generic JDBC Connection:

Give it a name:

Seam 2 Reference Guide

76

Page 82: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

JBoss Tools doesn't come with drivers for any databases, so you need to tell JBoss Tools where theMySQL JDBC driver is. Tell it about the driver by clicking ....

Locate MySQL 5, and hit Add...:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

77

Page 83: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Choose the MySQL JDBC Driver template:

Locate the jar on your computer by choosing Edit Jar/Zip:

Seam 2 Reference Guide

78

Page 84: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Review the username and password used to connect, and if correct, hit Ok.

Finally, choose the newly created driver:

If you are working with an existing data model, make sure you tell JBoss Tools that the tables alreadyexist in the database.

Review the username and password used to connect, test the connection using the Test Connectionbutton, and if it works, hit Finish:

Finally, review the package names for your generated beans, and if you are happy, click Finish:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

79

Page 85: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

JBoss has sophisticated support for hot re-deployment of WARs and EARs. Unfortunately, due to bugsin the JVM, repeated redeployment of an EAR—which is common during development—eventuallycauses the JVM to run out of perm gen space. For this reason, we recommend running JBoss in a JVMwith a large perm gen space at development time. We suggest the following values:

If you don't have so much memory available, the following is our minimum recommendation:

Locate the server in the JBoss Server View, right click on the server and select Edit LaunchConfiguration:

-Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512

-Xms256m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=256

Seam 2 Reference Guide

80

Page 86: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Then, alter the VM arguments:

If you don't want to bother with this stuff now, you don't have to—come back to it later, when you getyour first OutOfMemoryException.

To start JBoss, and deploy the project, just right click on the server you created, and click Start, (orDebug to start in debug mode):

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

81

Page 87: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Don't get scared by the XML configuration documents that were generated into the project directory.They are mostly standard Java EE stuff, the stuff you need to create once and then never look atagain, and they are 90% the same between all Seam projects.

3.3. CREATING A NEW ACTION

If you're used to traditional action-style web frameworks, you're probably wondering how you cancreate a simple web page with a stateless action method in Java.

First, select New -> Seam Action:

Now, enter the name of the Seam component. JBoss Tools selects sensible defaults for other fields:

Seam 2 Reference Guide

82

Page 88: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Finally, hit Finish.

Now go to http://localhost:8080/helloworld/ping.seam and click the button. You can seethe code behind this action by looking in the project src directory. Put a breakpoint in the ping()method, and click the button again.

Finally, open the helloworld-test project, locate PingTest class, right click on it, and choose RunAs -> TestNG Test:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

83

Page 89: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

3.4. CREATING A FORM WITH AN ACTION

The first step is to create a form. Select New -> Seam Form:

Now, enter the name of the Seam component. JBoss Tools selects sensible defaults for other fields:

Seam 2 Reference Guide

84

Page 90: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Go to http://localhost:8080/helloworld/hello.seam. Then take a look at the generatedcode. Run the test. Try adding some new fields to the form and Seam component (note, you don't needto restart the app server each time you change the code in src/action as Seam hot reloads thecomponent for you Section 3.6, “Seam and incremental hot deployment with JBoss Tools” ).

3.5. GENERATING AN APPLICATION FROM AN EXISTING DATABASE

Manually create some tables in your database. (If you need to switch to a different database, create anew project, and select the correct database). Then, select New -> Seam Generate Entities:

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

85

Page 91: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

JBoss Tools gives you the option to either reverse engineer entities, components and views from adatabase schema or to reverse engineer components and views from existing JPA entities. We're goingto do Reverse engineer from database.

Restart the deployment:

Then go to http://localhost:8080/helloworld. You can browse the database, edit existingobjects, and create new objects. If you look at the generated code, you'll probably be amazed howsimple it is! Seam was designed so that data access code is easy to write by hand, even for people whodon't want to cheat by using reverse engineering.

3.6. SEAM AND INCREMENTAL HOT DEPLOYMENT WITH JBOSSTOOLS

JBoss Tools supports incremental hot deployment of:

any facelets page

any pages.xml file

out of the box.

Seam 2 Reference Guide

86

Page 92: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

But if we want to change any Java code, we still need to do a full restart of the application by doing aFull Publish.

But if you really want a fast edit/compile/test cycle, Seam supports incremental redeployment ofJavaBean components. To make use of this functionality, you must deploy the JavaBean componentsinto the WEB-INF/dev directory, so that they will be loaded by a special Seam classloader, instead ofby the WAR or EAR classloader.

You need to be aware of the following limitations:

the components must be JavaBean components, they cannot be EJB3 beans (we are workingon fixing this limitation)

entities can never be hot-deployed

components deployed via components.xml may not be hot-deployed

the hot-deployable components will not be visible to any classes deployed outside of WEB-INF/dev

Seam debug mode must be enabled and jboss-seam-debug.jar must be in WEB-INF/lib

You must have the Seam filter installed in web.xml

You may see errors if the system is placed under any load and debug is enabled.

If you create a WAR project using JBoss Tools, incremental hot deployment is available out of the boxfor classes in the src/action source directory. However, JBoss Tools does not support incrementalhot deployment for EAR projects.

CHAPTER 3. GETTING STARTED WITH SEAM, USING JBOSS TOOLS

87

Page 93: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2There are two approaches to migrating your Seam 1.2 application to Seam 2. The recommendedapproach, described in Section 4.1, “Creating a new project skeleton using seam-gen” is to create anew project using seam-gen in Seam 2, and migrate your code across. We recognize that manyprojects may have extensive customizations to their project, so we also provide instructions for how toupgrade your project in-situ in Section 4.2, “In place migration” Due to the number of changesintroduced between Seam 1.2 and Seam 2, this may not always be a straightforward process.

However you decide to migrate your application, you will need to alter your code, as many componentshave moved. Section 4.3, “Updating your code” details those changes.

4.1. CREATING A NEW PROJECT SKELETON USING SEAM-GEN

Start by creating a new skeleton Seam project. In your Seam 2 directory run:

Customize the defaults as needed. You will want to set the location of the JBoss EnterpriseApplication Platform, name your project and select an EAR or WAR as needed; you can accept thedefaults for Java package names (as we aren't going to use the reverse engineering features of seam-gen); you'll want to set your JDBC driver, URL, username and password correctly, and configureHibernate to drop and recreate tables if so desired.

Now, we are ready to import your existing code and views into the new structure. The simplest way todo this is to import both projects into your favorite IDE, and copy your code and views across.

Continue on to Section 4.3, “Updating your code” for details regarding the changes needed to yourcode, and configuration files.

4.2. IN PLACE MIGRATION

This requires more work, but is suitable for more complex projects. The steps below may not be anexhaustive list, so if you have any extra steps please report them through the Customer SupportPortal.

4.2.1. Migrating to JSF 1.2

WARNING

You only need to do this if you are migrating from the community edition of Seam,JBoss Enterprise Application Platform 4.2 and 4.3 ship with version 2.0.2.FP ofSeam, which uses JSF 1.2.

Seam 2.0 requires JSF 1.2, and JBoss Enterprise Application Platform supports Sun's JSF RI. To switchto JSF 1.2, you need to remove the MyFaces listener:

~/seam_2_0$ ./seam setup

<!--Remove for Seam 2-->

Seam 2 Reference Guide

88

Page 94: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

from your web.xml.

The JSF RI doesn't require you to specify a listener.

NOTE

Due to an incompatibility between Seam and MyFaces, you had to use client side statesaving in Seam 1.2. Switching to the JSF RI 1.2 lifts this restriction. So remove thecontext param javax.faces.STATE_SAVING_METHOD.

4.2.2. Migrating web.xml to Seam 2

First change the web-app version from 2.4 to 2.5. There is also change in j2ee to javaee in namespaceURL. Declaration of the web.xml should look like:

In your Seam 1.2 app you may have specified some Seam specific configuration in web.xml. First, we'lldiscuss all the Seam related elements you need in web.xml, not just those that have changed, notingany changes.

In Seam 2, you need to specify a listener (just as you did in Seam 1.2):

Modify the Seam master filter (note the package of the class changed):

If any other Seam Filters (for example the SeamExceptionFilter) are enumerated, they should beremoved.

<!--<listener> <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class></listener>-->

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> ...</web-app>

<listener> <listener-class>org.jboss.seam.servlet.SeamListener</listener-class></listener>

<filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class></filter>

<filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2

89

Page 95: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Finally, you should have the Seam resource servlet (just as you did in Seam 1.2):

Seam 2 will automatically install RichFaces' Ajax4JSF if it is present in your project so you shouldmake sure the Ajax4JSF filter is not declared:

Next, we will describe the changes you need to make to your JSF ViewHandler configuration.Previously the configuration you used depended on whether you were using Seam's EL enhancementsor Ajax4JSF or both. In Seam 2 you should use the default FaceletViewHandler.

Seam 1.2 required you to use a special JSF ViewHandler to install it's EL enhancement (whilst inSeam 2 the EL enhancement is built in). The version of Ajax4JSF distributed with Seam 1.2 requiredyou to specify which ViewHandler to use when it was in use. Make sure that the Ajax4JSFconfiguration is removed from your web.xml: file:

4.2.3. Migrating faces-config.xml to Seam 2

Remove the DTD on the document and add the XML Schema declarations to the root tag:

<servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class></servlet> <servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern></servlet-mapping>

<!--Remove for Seam 2--><!--<filter> <display-name>Ajax4jsf Filter</display-name> <filter-name>ajax4jsf</filter-name> <filter-class>org.ajax4jsf.Filter</filter-class></filter>--> <!--Remove for Seam 2--><!--<filter-mapping> <filter-name>ajax4jsf</filter-name> <url-pattern>*.seam</url-pattern></filter-mapping>-->

<!--Remove for Seam 2--><!--<context-param> <param-name>org.ajax4jsf.VIEW_HANDLERS</param-name> <param-value>org.jboss.seam.ui.facelet.SeamFaceletViewHandler</param-value></context-param>-->

<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee

Seam 2 Reference Guide

90

Page 96: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam 1.2 required you to specify either the SeamPhaseListener (Seam Managed Transaction wereare disabled) or SeamTransactionalPhaseListener (Seam Managed Transactions are enabled) in faces-config.xml. Seam 2 allows you to enable or disable Seam Managed Transactions in components.xml, and installs the phase listener for you. Therefore, you should remove any referenceto SeamPhaseListener or SeamTransactionalPhaseListener from faces-config.xml.

Seam Managed Transaction are enabled by default, to disable Seam Managed Transactions, set transaction-management-enabled to false:

You may have specified SeamELResolver in faces-config.xml as an old workaround to a knownbug; this is no longer required.

Finally remove FaceletViewHandler configuration:

4.2.4. Deployment structure changes

If you have an EAR application there are some deployment structure changes needed. You shouldmove all the dependencies which you previously declared as modules in application.xml to the lib/ directory of your EAR except jboss-seam.jar which should be declared as an EJB module in application.xml. Remove the unneeded module declarations from application.xml.

4.2.5. Migration to JBoss Embedded

Support for deployment to JBoss Embeddable EJB3 and JBoss Microcontainer has been removed.Instead, the new JBoss Embedded distribution gives you a full set of EE-compatible APIs with simplifieddeployment.

For testing, you need the jars in Seam's lib/test, the jars in Seam's lib/ directory, your test classesand application classes together with the bootstrap/ directory in your classpath. SeamTest willautomatically start the container.

WARNING

You must order the classpath correctly when using Embedded with SeamTest.Make sure the jars in lib/test come first in any classpath order. For example,when using Ant, they should be declared above any other libraries in the testclasspath.

http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"> ...</faces-config>

<core:init transaction-management-enabled="false"/>

<application> <view-handler>com.sun.facelets.FaceletViewHandler</view-handler></application>

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2

91

Page 97: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If you want to run tests using the Eclipse TestNG plugin, you will need to add these jars to the top ofyour TestNG classpath. Using the Run Dialog, select the xml suite to run, and add /lib/test/jboss-embedded-all.jar, /lib/test/hibernate-all.jar, /lib/test/thirdparty-all.jar, /lib/jboss-embedded-api.jar, /lib/jboss-deployers-client-spi.jar, /lib/jboss-deployers-core-spi.jar, and /bootstrap as the first entries in the User classpath.

NOTE

JBoss Embedded is able to bootstrap a datasource from a -ds.xml file, so there is nolonger a need for jboss-beans.xml.

4.3. UPDATING YOUR CODE

IMPORTANT

Do not forget to update the XSD's in pages.xml and components.xml to point tothose for Seam 2. Just change the suffix from -1.2.xsd to -2.0.xsd.

4.3.1. Built-in Component changes

Seam's built-in components have undergone a major reorganization designed to organize them foreasier learning, and to isolate dependencies upon particular technologies like JSF into specificpackages.

You will need to update both your components.xml file and any references in the Java code.

In general:

Persistence-related components are located in org.jboss.seam.persistence

jBPM related components are located in org.jboss.seam.bpm

JSF-related components are located in org.jboss.seam.faces

Servlet-related components are located in org.jboss.seam.web

Components related to asynchronously are located in org.jboss.seam.async

i18n-related components are located in org.jboss.seam.international

The Pageflow component are located in org.jboss.seam.pageflow

The Pages component are located in org.jboss.seam.navigation

The following presents a non-exhaustive list of changed components:

Component's in Seam 2

Component name: actor

Seam 1.2 Old class: org.jboss.seam.core.Actor

Seam 2 class: org.jboss.seam.bpm.Actor

Seam 2 Reference Guide

92

Page 98: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

XML Element: <bpm:actor />

XML namespace: http://jboss.com/products/seam/bpm

XSD: http://jboss.com/products/seam/bpm-2.0.xsd

Component name: businessProcess

Seam 1.2 Old class: org.jboss.seam.core.BusinessProcess

Seam 2 class: org.jboss.seam.bpm.BusinessProcess

Component name: dispatcher

Seam 1.2 Old class: org.jboss.seam.core.Dispatcher

Seam 2 class: org.jboss.seam.async.Dispatcher (now an interface)

XML Element: <async:timer-service-dispatcher />

XML namespace: http://jboss.com/products/seam/async

XSD: http://jboss.com/products/seam/async-2.0.xsd

Component name: Specified by user

Seam 1.2 Old class: javax.persistence.EntityManagerFactory

Seam 2 class: javax.persistence.EntityManagerFactory

XML Element: <persistence:entity-manager-factory />

XML namespace: http://jboss.com/products/seam/persistence

XSD: http://jboss.com/products/seam/persistence-2.0.xsd

Component name: exceptions

Seam 1.2 Old class: org.jboss.seam.core.Exceptions

Seam 2 class: org.jboss.seam.exception.Exceptions

Component name: facesMessages

Seam 1.2 Old class: org.jboss.seam.core.FacesMessages

Seam 2 class: org.jboss.seam.faces.FacesMessages

Component name: facesPage

Seam 1.2 Old class: org.jboss.seam.core.FacesPage

Seam 2 class: org.jboss.seam.faces.FacesPage

Component name: Specified by user

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2

93

Page 99: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam 1.2 Old class: org.jboss.seam.core.Filter

Seam 2 class: org.jboss.seam.persistence.Filter

XML Element: <persistence:filter />

XML namespace: http://jboss.com/products/seam/persistence

XSD: http://jboss.com/products/seam/persistence-2.0.xsd

Component name: Specified by user

Seam 1.2 Old class: org.jboss.seam.core.HibernateSessionFactory

Seam 2 class: org.jboss.seam.persistence.HibernateSessionFactory

XML Element: <persistence:hibernate-session-factory />

XML namespace: http://jboss.com/products/seam/persistence

XSD: http://jboss.com/products/seam/persistence-2.0.xsd

Component name: httpError

Seam 1.2 Old class: org.jboss.seam.core.HttpError

Seam 2 class: org.jboss.seam.faces.HttpError

Component name: image

Seam 1.2 Old class: org.jboss.seam.core.Image

Seam 2 class: removed

Component name: isUserInRole

Seam 1.2 Old class: Map<String, Boolean>

Seam 2 class: org.jboss.seam.faces.IsUserInRole

Component name: jbpm

Seam 1.2 Old class: org.jboss.seam.core.Jbpm

Seam 2 class: org.jboss.seam.bpm.Jbpm

XML Element: bpm

XML namespace: http://jboss.com/products/seam/bpm

XSD: http://jboss.com/products/seam/bpm-2.0.xsd

Seam 1.2 Old class: org.jboss.seam.core.LocalDispatcher

Seam 2 class: org.jboss.seam.async.LocalDispatcher

Seam 2 Reference Guide

94

Page 100: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Component name: localeSelector

Seam 1.2 Old class: org.jboss.seam.core.LocaleSelector

Seam 2 class: org.jboss.seam.international.LocaleSelector

XML Element: <international:locale-selector />

XML namespace: http://jboss.com/products/seam/international

XSD: http://jboss.com/products/seam/international-2.0.xsd

Seam 1.2 Old class: org.jboss.seam.core.LocalTransactionListener

Seam 2 class: removed

Component name: Specified by user

Seam 1.2 Old class: org.jboss.seam.core.ManagedHibernateSession

Seam 2 class: org.jboss.seam.persistence.ManagedHibernateSession

XML Element: <persistence:managed-hibernate-session />

XML namespace: http://jboss.com/products/seam/persistence

XSD: http://jboss.com/products/seam/persistence-2.0.xsd

Component name: jbpmContext

Seam 1.2 Old class: org.jboss.seam.core.ManagedJbpmContext

Seam 2 class: org.jboss.seam.bpm.ManagedJbpmContext

Component name: Specified by user

Seam 1.2 Old class: org.jboss.seam.core.ManagedEntityManager

Seam 2 class: org.jboss.seam.persistence.ManagedEntityManager

XML Element: <persistence:managed-entity-manager />

XML namespace: http://jboss.com/products/seam/persistence

XSD: http://jboss.com/products/seam/persistence-2.0.xsd

Component name: microcontainer

Seam 1.2 Old class: org.jboss.seam.core.Microcontainer

Seam 2 class: removed

Component name: pageflow

Seam 1.2 Old class: org.jboss.seam.core.Pageflow

Seam 2 class: org.jboss.seam.bpm.Pageflow

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2

95

Page 101: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Component name: pages

Seam 1.2 Old class: org.jboss.seam.core.Pages

Seam 2 class: org.jboss.seam.navigation.Pages

XML Element: <navigation:pages/>

XML namespace: http://jboss.com/products/seam/navigation

XSD: http://jboss.com/products/seam/navigation-2.0.xsd

Component name: persistenceContexts

Seam 1.2 Old class: org.jboss.seam.core.PersistenceContexts

Seam 2 class: org.jboss.seam.persistence.PersistenceContexts

Component name: pooledTask

Seam 1.2 Old class: org.jboss.seam.core.PooledTask

Seam 2 class: org.jboss.seam.bpm.PooledTask

Component name: processInstanceFinder

Seam 1.2 Old class: org.jboss.seam.core.ProcessInstanceFinder

Seam 2 class: org.jboss.seam.bpm.ProcessInstanceFinder

Component name: redirect

Seam 1.2 Old class: org.jboss.seam.core.Redirect

Seam 2 class: org.jboss.seam.faces.Redirect

Component name: switcher

Seam 1.2 Old class: org.jboss.seam.core.Switcher

Seam 2 class: org.jboss.seam.faces.Switcher

Component name: timeZoneSelector

Seam 1.2 Old class: org.jboss.seam.core.TimeZoneSelector

Seam 2 class: org.jboss.seam.international.TimeZoneSelector

XML Element: <international:time-zone-selector />

XML namespace: http://jboss.com/products/seam/international

XSD: http://jboss.com/products/seam/international-2.0.xsd

Component name: transition

Seam 2 Reference Guide

96

Page 102: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam 1.2 Old class: org.jboss.seam.core.Transistion

Seam 2 class: org.jboss.seam.bpm.Transition

4.3.2. Annotation changes in Seam 2

Annotations have also moved to reflect their purpose. In

BPM-related annotations are located in org.jboss.seam.annotations.bpm

@BeginTask

@CreateProcess

@EndTask

@ResumeProcess

@StartTask

@Transition

JSF-related annotations are located in org.jboss.seam.annotations.faces

@Converter

@Validator

Interceptor annotations are located in org.jboss.seam.annotations.intercept

@AroundInvoke

@BypassIntercetors

@Interceptor

@Interceptors

Annotations related to asynchronously are located in org.jboss.seam.annotations.async

@Asynchronous

@Duration

@Expiration

@FinalExpiration

@IntervalCron

@IntervalDuration

The annotation to inject a request parameter is located in org.jboss.seam.annotations.web

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2

97

Page 103: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

@RequestParameter

The annotation required to make a method accessible via remoting is located in org.jboss.seam.annotations.remoting

The annotation to apply a security restriction to the component is located in org.jboss.seam.annotations.security

@Restrict

Exception handling annotations moved to org.jboss.seam.annotations.exception

@HttpError

@Redirect

NOTE

You also need to replace @Intercept(NEVER) with @BypassInterceptors.

4.3.3. Other changes needed to components.xml

The conversation-is-long-running-parameter attribute has been removed from Seam (anddoesn't have a replacement); remove it from <core:init />.

As described in Section 4.2.5, “Migration to JBoss Embedded” , Embeddable EJB3 and Microcontainersupport has been removed, so you need to remove <core:ejb/> and <core:microcontainer/>from components.xml.

The EE transaction integration has been redesigned, so the transaction listener component name haschanged. Replace <core:transaction-listener/> with <transaction:ejb-transaction/>.

The resource bundle loader has been split out of the resource bundle, so you should replace <core:resource-bundle/> with <core:resource-loader/>.

Finally, you should change any expression attributes to execute:

4.3.4. Migration to jBPM 3.2

If you are using jBPM for business processes, you need to add the tx service to jbpm.cfg.xml:

NOTE

You don't need to do this if you are just using jBPM for pageflows.

4.3.5. Migration to RichFaces 3.1

<event type="org.jboss.seam.notLoggedIn"> <action execute="#{redirect.captureCurrentView}"/></event>

<service name="tx" factory="org.jbpm.tx.TxServiceFactory" />

Seam 2 Reference Guide

98

Page 104: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If you are using RichFaces or Ajax4jsf, a major reorganization of the project has occurred. The jars ajax4jsf.jar and richfaces.jar have been replaced by richfaces-api.jar (which should goin your ear lib/ directory), richfaces-impl.jar and richfaces-ui.jar (both of which go in WEB-INF/lib).

<s:selectDate> has been deprecated in favor of <rich:calendar>. No more development will be done on<s:selectDate>. You can remove the styles related to the data picker from your stylesheet to save onunnecessary bandwidth use.

You should check the RichFaces documentation for more information on parameter name changes andnamespace changes.

4.3.6. Changes to Seam UI

As most JSF component sets provide a date selector, the Seam date selector (<s:selectDate>) hasbeen deprecated. You should replace it with the date selector from the component set you use.

Selector <s:decorate/> has become a naming container. Therefore client ids have changed from fooForm:fooInput to fooForm:foo:fooInput, assuming the following declaration:

If you do not provide an id to <s:decorate>, one will be generated by JSF.

4.3.7. Changes to seam-gen

There was a change in seam-gen regarding how the generated classes are organized when generate-entities is executed.

Old way:

src/model/com/domain/projectname/model/EntityName.java

src/action/com/domain/projectname/model/EntityNameHome.java

src/action/com/domain/projectname/model/EntityNameList.java

New way:

src/model/com/domain/projectname/model/EntityName.java

src/action/com/domain/projectname/action/EntityNameHome.java

src/action/com/domain/projectname/action/EntityNameList.java

Home and Query objects are action components, not model components and are therefore placed inthe action package. This change makes the conventions followed by generate-entities consistent withthe conventions used in the new-entity command.

Remember, model classes are kept separate because they cannot be hot reloaded.

Due to the change from JBoss Embeddable EJB3 to JBoss Embedded for testing, it is recommended

<h:form id="fooForm"> <s:decorate id="foo"> <h:inputText id="fooInput" value="#{bean.property}"/> </s:decorate></h:form>

CHAPTER 4. MIGRATING FROM SEAM 1.2 TO SEAM 2

99

Page 105: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

that you generate a project using seam-gen from Seam 2 and borrow the build.xml file from thatproject. If you have made significant changes to the build.xml in your project, you may want to focuson just migrating the test-related targets.

In order for tests to work under JBoss Embedded, you need to change the value of the <datasource>element in resources/META-INF/persistence-test.xml (or persistence-test-war.xml) tojava:/DefaultDS. The alternative is to deploy a *-ds.xml file to the bootstrap/deploy folderand use the JNDI name defined by that file.

If you use the build.xml from a Seam 2 seam-gen project, you will also need the deployed-*.listfile(s). These files define which JAR files are packaged in the EAR or WAR. They were introduced toexternalize this set of JARS from the build.xml file.

To accommodate a change in the RichFaces panel, you need to add the following style to yourstylesheet. Otherwise, your search criteria block in pages created by generate-entities will bleed intothe table of results.

.rich-stglpanel-body { overflow: auto;}

Seam 2 Reference Guide

100

Page 106: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 5. THE CONTEXTUAL COMPONENT MODELThe two core concepts in Seam are the notion of a context and the notion of a component. Componentsare stateful objects, usually EJBs, and an instance of a component is associated with a context, andgiven a name in that context. Bijection provides a mechanism for aliasing internal component names(instance variables) to contextual names, allowing component trees to be dynamically assembled, andreassembled by Seam.

Let us start by describing the contexts built in to Seam.

5.1. SEAM CONTEXTS

Seam contexts are created and destroyed by the framework. The application does not control contextdemarcation via explicit Java API calls. Context are usually implicit. In some cases, however, contextsare demarcated via annotations.

The basic Seam contexts are:

Stateless context

Event (or request) context

Page context

Conversation context

Session context

Business process context

Application context

You will recognize some of these contexts from servlet and related specifications. However, two ofthem might be new to you: conversation context, and business process context. One reason statemanagement in web applications is so fragile and error-prone is that the three built-in contexts(request, session and application) are not especially meaningful from the point of view of the businesslogic. A user login session, for example, is a fairly arbitrary construct in terms of the actual applicationwork flow. Therefore, most Seam components are scoped to the conversation or business processcontexts, since they are the contexts which are most meaningful in terms of the application.

Let us look at each context in turn.

5.1.1. Stateless context

Components which are truly stateless (stateless session beans, primarily) always live in the statelesscontext (this is really a non-context). Stateless components are not very interesting, and are arguablynot very object-oriented. Nevertheless, they are important and often useful.

5.1.2. Event context

The event context is the narrowest stateful context, and is a generalization of the notion of the webrequest context to cover other kinds of events. Nevertheless, the event context associated with thelifecycle of a JSF request is the most important example of an event context, and the one you will workwith most often. Components associated with the event context are destroyed at the end of therequest, but their state is available and well-defined for at least the lifecycle of the request.

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

101

Page 107: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

When you invoke a Seam component via RMI, or Seam Remoting, the event context is created anddestroyed just for the invocation.

5.1.3. Page context

The page context allows you to associate state with a particular instance of a rendered page. You caninitialize state in your event listener, or while actually rendering the page, and then have access to itfrom any event that originates from that page. This is especially useful for functionality like clickablelists, where the list is backed by changing data on the server side. The state is actually serialized to theclient, so this construct is extremely robust with respect to multi-window operation and the backbutton.

5.1.4. Conversation context

The conversation context is a truly central concept in Seam. A conversation is a unit of work from thepoint of view of the user. It might span several interactions with the user, several requests, and severaldatabase transactions. But to the user, a conversation solves a single problem. For example, book hotel,approve contract, create order are all conversations. You might like to think of a conversationimplementing a single use case or user story, but the relationship is not necessarily quite exact.

A conversation holds state associated with what the user is doing now, in this window. A single user mayhave multiple conversations in progress at any point in time, usually in multiple windows. Theconversation context allows us to ensure that state from the different conversations does not collideand cause bugs.

It might take some time to get used to thinking of applications in terms of conversations, but once youget used to it the advantages to such a setup will be apparent to you.

Some conversations last for just a single request. Conversations that span multiple requests must bedemarcated using annotations provided by Seam.

Some conversations are also tasks. A task is a conversation that is significant in terms of a long-running business process, and has the potential to trigger a business process state transition when it issuccessfully completed. Seam provides a special set of annotations for task demarcation.

Conversations may be nested, with one conversation taking place within a wider conversation. This isan advanced feature.

Usually, conversation state is actually held by Seam in the servlet session between requests. Seamimplements configurable conversation timeout, automatically destroying inactive conversations, andthus ensuring that the state held by a single user login session does not grow without bound if the userabandons conversations.

Seam serializes processing of concurrent requests that take place in the same long-runningconversation context, in the same process.

Alternatively, Seam may be configured to keep the conversational state in the client browser.

5.1.5. Session context

A session context holds state associated with the user login session. While there are some cases whereit is useful to share state information between several conversations, it is generally not advised to usethe session context for holding components other than global information about the logged in user.

In a JSR-168 portal environment, the session context represents the portlet session.

Seam 2 Reference Guide

102

Page 108: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

5.1.6. Business process context

The business process context holds state associated with the long running business process. Thisstate is managed and made persistent by the BPM engine (JBoss jBPM). The business process spansmultiple interactions with multiple users, so this state is shared between multiple users, but in a well-defined manner. The current task determines the current business process instance, and the lifecycleof the business process is defined externally using a process definition language, so there are no specialannotations for business process demarcation.

5.1.7. Application context

The application context is the familiar servlet context from the servlet spec. Application context ismainly useful for holding static information such as configuration data, reference data or metamodels.For example, Seam stores its own configuration and metamodel in the application context.

5.1.8. Context variables

A context defines a namespace, a set of context variables. These work much the same as session orrequest attributes in the servlet spec. You may bind any value you like to a context variable, butusually we bind Seam component instances to context variables.

So, within a context, a component instance is identified by the context variable name (this is usually,but not always, the same as the component name). You may programmatically access a namedcomponent instance in a particular scope via the Contexts class, which provides access to severalthread-bound instances of the Context interface:

You may also set or change the value associated with a name:

Usually, however, we obtain components from a context via injection, and place component instancesinto a context via querying.

5.1.9. Context search priority

Sometimes, as above, component instances are obtained from a particular known scope. Other times,all stateful scopes are searched, in priority order. The order is as follows:

Event context

Page context

Conversation context

Session context

Business process context

Application context

You can perform a priority search by calling Contexts.lookupInStatefulContexts(). Wheneveryou access a component by name from a JSF page, a priority search occurs.

User user = (User) Contexts.getSessionContext().get("user");

Contexts.getSessionContext().set("user", user);

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

103

Page 109: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

5.1.10. Concurrency model

Neither the servlet nor EJB specifications define any facilities for managing concurrent requestsoriginating from the same client. The servlet container simply lets all threads run concurrently andleaves enforcing threadsafeness to application code. The EJB container allows stateless componentsto be accessed concurrently, and throws an exception if multiple threads access a stateful sessionbean.

This behavior might have been okay in older web applications which were based around precise,synchronous requests. But for modern applications which make heavy use of many precise,asynchronous (AJAX) requests, concurrency is a fact of life, and must be supported by theprogramming model. Seam weaves a concurrency management layer into its context model.

The Seam session and application contexts are multi-threaded. Seam will allow concurrent requests ina context to be processed concurrently. The event and page contexts are by nature single threaded.The business process context is strictly speaking multi-threaded, but in practice concurrency issufficiently rare that this fact may be disregarded most of the time. Finally, Seam enforces a singlethread per conversation per process model for the conversation context by serializing concurrentrequests in the same long-running conversation context.

Since the session context is multi-threaded, and often contains volatile state, session scopecomponents are always protected by Seam from concurrent access. Seam serializes requests tosession scope session beans and JavaBeans by default (and detects and breaks any deadlocks thatoccur). This is not the default behavior for application scoped components however, since applicationscoped components do not usually hold volatile state and because synchronization at the global levelis extremely expensive to the application. However, you can force a serialized threading model on anysession bean or JavaBean component by adding the @Synchronized annotation.

This concurrency model means that AJAX clients can safely use volatile session and conversationalstate, without the need for any special work on the part of the developer.

5.2. SEAM COMPONENTS

Seam components are POJOs (Plain Old Java Objects). In particular, they are JavaBeans or EJB 3.0enterprise beans. While Seam does not require that components be EJBs and can even be used withoutan EJB 3.0 compliant container, Seam was designed with EJB 3.0 in mind and includes deepintegration with EJB 3.0. Seam supports the following component types.

EJB 3.0 stateless session beans

EJB 3.0 stateful session beans

EJB 3.0 entity beans

JavaBeans

EJB 3.0 message-driven beans

5.2.1. Stateless session beans

Stateless session bean components are not able to hold a state across multiple invocations. Therefore,they usually work by operating upon the state of other components in the various Seam contexts. Theymay be used as JSF action listeners, but cannot provide properties to JSF components for display.

Stateless session beans always live in the stateless context.

Seam 2 Reference Guide

104

Page 110: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Stateless session beans can be accessed concurrently as a new instance is used for each request.Assigning the instance to the request is the responsibility of the EJB3 container (normally instanceswill be allocated from a reusable pool meaning that you may find any instance variables contain datafrom previous uses of the bean).

Seam stateless session bean components may be instantiated using Component.getInstance() or @In(create=true). They should not be directly instantiated via JNDI lookup or the new operator.

5.2.2. Stateful session beans

Stateful session bean components are able to hold state not only across multiple invocations of thebean, but also across multiple requests. Application state that does not belong in the database shouldusually be held by stateful session beans. This is a major difference between Seam and many other webapplication frameworks. Instead of sticking information about the current conversation directly in the HttpSession, you should keep it in instance variables of a stateful session bean that is bound to theconversation context. This allows Seam to manage the lifecycle of this state for you, and ensure thatthere are no collisions between state relating to different concurrent conversations.

Stateful session beans are often used as JSF action listener, and as backing beans that provideproperties to JSF components for display or form submission.

By default, stateful session beans are bound to the conversation context. They may never be bound tothe page or stateless contexts.

Concurrent requests to session-scoped stateful session beans are always serialized by Seam.

Seam stateful session bean components may be instantiated using Component.getInstance() or @In(create=true). They should not be directly instantiated via JNDI lookup or the new operator.

5.2.3. Entity beans

Entity beans may be bound to a context variable and function as a seam component. Because entitieshave a persistent identity in addition to their contextual identity, entity instances are usually boundexplicitly in Java code, rather than being instantiated implicitly by Seam.

Entity bean components do not support bijection or context demarcation, neither does invocation of anentity bean trigger validation.

Entity beans are not usually used as JSF action listeners, but do often function as backing beans thatprovide properties to JSF components for display or form submission. In particular, it is common to usean entity as a backing bean, together with a stateless session bean action listener to implementcreate/update/delete type functionality.

By default, entity beans are bound to the conversation context. They may never be bound to thestateless context.

Seam entity bean components may be instantiated using Component.getInstance(), @In(create=true) or directly using the new operator.

NOTE

In a clustered environment it is somewhat less efficient to bind an entity bean directly toa conversation or session scoped Seam context variable than it would be to hold areference to the entity bean in a stateful session bean. For this reason, not all Seamapplications define entity beans to be Seam components.

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

105

Page 111: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

5.2.4. JavaBeans

Javabeans may be used just like a stateless or stateful session bean. However, they do not provide thefunctionality of a session bean (declarative transaction demarcation, declarative security, efficientclustered state replication, EJB 3.0 persistence, timeout methods, etc).

In a later chapter, we show you how to use Seam and Hibernate without an EJB container. In this usecase, components are JavaBeans instead of session beans.

NOTE

In many application servers it is somewhat less efficient to cluster conversation orsession scoped Seam JavaBean components than it is to cluster stateful session beancomponents.

By default, JavaBeans are bound to the event context.

Concurrent requests to session-scoped JavaBeans are always serialized by Seam.

Seam JavaBean components may be instantiated using Component.getInstance() or @In(create=true). They should not be directly instantiated using the new operator.

5.2.5. Message-driven beans

Message-driven beans may function as a seam component. However, message-driven beans are calledquite differently to other Seam components - instead of invoking them via the context variable, theylisten for messages sent to a JMS queue or topic.

Message-driven beans may not be bound to a Seam context. Neither do they have access to thesession or conversation state of their caller. However, they do support bijection and some other Seamfunctionality.

Message-driven beans are never instantiated by the application. They are instantiated by the EJBcontainer when a message is received.

5.2.6. Interception

In order to perform bijection, context demarcation, validation, etc, Seam must intercept componentinvocations. For JavaBeans, Seam is in full control of instantiation of the component, and no specialconfiguration is needed. For entity beans, interception is not required since bijection and contextdemarcation are not defined. For session beans, we must register an EJB interceptor for the sessionbean component. We could use an annotation, as follows:

But a much better way is to define the interceptor in ejb-jar.xml.

@Stateless@Interceptors(SeamInterceptor.class)public class LoginAction implements Login { ... }

<interceptors> <interceptor> <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-

Seam 2 Reference Guide

106

Page 112: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

5.2.7. Component names

All seam components need a name. We can assign a name to a component using the @Name annotation:

This name is the seam component name and is not related to any other name defined by the EJBspecification. However, seam component names work just like JSF managed bean names and you canthink of the two concepts as identical.

@Name is not the only way to define a component name, but we always need to specify the namesomewhere. If we don't, then none of the other Seam annotations will function.

Just like in JSF, a seam component instance is usually bound to a context variable with the same nameas the component name. So, for example, we would access the LoginAction using Contexts.getStatelessContext().get("loginAction"). In particular, whenever Seam itselfinstantiates a component, it binds the new instance to a variable with the component name. However,again like JSF, it is possible for the application to bind a component to some other context variable byprogrammatic API call. This is only useful if a particular component serves more than one role in thesystem. For example, the currently logged in User might be bound to the currentUser sessioncontext variable, while a User that is the subject of some administration functionality might be boundto the user conversation context variable.

For very large applications, and for built-in seam components, qualified names are often used.

We may use the qualified component name both in Java code and in JSF's expression language:

Since this is noisy, Seam also provides a means of aliasing a qualified name to a simple name. Add a linelike this to the components.xml file:

class> </interceptor></interceptors> <assembly-descriptor> <interceptor-binding> <ejb-name>*</ejb-name> <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class> </interceptor-binding></assembly-descriptor>

@Name("loginAction")@Statelesspublic class LoginAction implements Login { ... }

@Name("com.jboss.myapp.loginAction")@Statelesspublic class LoginAction implements Login { ... }

<h:commandButton type="submit" value="Login" action="#{com.jboss.myapp.loginAction.login}"/>

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

107

Page 113: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

All of the built-in Seam components have qualified names, but most of them are aliased to a simplename by the components.xml file included in the Seam jar.

5.2.8. Defining the component scope

We can override the default scope (context) of a component using the @Scope annotation. This lets usdefine what context a component instance is bound to, when it is instantiated by Seam.

org.jboss.seam.ScopeType defines an enumeration of possible scopes.

5.2.9. Components with multiple roles

Some Seam component classes can fulfill more than one role in the system. For example, we oftenhave a User class which is usually used as a session-scoped component representing the current userbut is used in user administration screens as a conversation-scoped component. The @Roleannotation lets us define an additional named role for a component, with a different scope; allowing forthe same component class to bind to different context variables. (Any Seam component instance maybe bound to multiple context variables, but this lets us do it at the class level, and take advantage ofauto-instantiation.)

The @Roles annotation lets us specify as many additional roles as we like.

5.2.10. Built-in components

Seam is implemented mostly as a set of built-in Seam interceptors (see later) and Seam components.This makes it easy for applications to interact with built-in components at runtime or even customize

<factory name="loginAction" scope="STATELESS" value="#{com.jboss.myapp.loginAction}"/>

@Name("user")@Entity@Scope(SESSION)public class User { ... }

@Name("user")@Entity@Scope(CONVERSATION)@Role(name="currentUser", scope=SESSION)public class User { ... }

@Name("user")@Entity@Scope(CONVERSATION)@Roles({@Role(name="currentUser", scope=SESSION), @Role(name="tempUser", scope=EVENT)})public class User { ... }

Seam 2 Reference Guide

108

Page 114: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

the basic functionality of Seam by replacing the built-in components with custom implementations. Thebuilt-in components are defined in the Seam namespace org.jboss.seam.core and the Javapackage of the same name.

The built-in components may be injected, just like any Seam components, but they also provideconvenient static instance() methods:

5.3. BIJECTION

Dependency injection or inversion of control is by now a familiar concept to most Java developers.Dependency injection allows a component to obtain a reference to another component by having thecontainer inject the other component to a setter method or instance variable. In all dependencyinjection implementations that we have seen, injection occurs when the component is constructed, andthe reference does not subsequently change for the lifetime of the component instance. For statelesscomponents, this is reasonable. From the point of view of a client, all instances of a particular statelesscomponent are interchangeable. On the other hand, Seam emphasizes the use of stateful components.So traditional dependency injection is no longer a very useful construct. Seam introduces the notion ofbijection as a generalization of injection. In contrast to injection, bijection is:

contextual - bijection is used to assemble stateful components from various different contexts(a component from a wider context may even have a reference to a component from a narrowercontext)

bidirectional - values are injected from context variables into attributes of the component beinginvoked, and also passed from the component attributes back out to the context, allowing thecomponent being invoked to manipulate the values of contextual variables simply by setting itsown instance variables

dynamic - since the value of contextual variables changes over time, and since Seamcomponents are stateful, bijection takes place every time a component is invoked

In essence, bijection lets you alias a context variable to a component instance variable, by specifyingthat the value of the instance variable is injected, outjected, or bothl; annotations is used to enablebijection.

The @In annotation specifies that a value should be injected, either into an instance variable:

or into a setter method:

FacesMessages.instance().add("Welcome back, #{user.name}!");

@Name("loginAction")@Statelesspublic class LoginAction implements Login { @In User user; ... }

@Name("loginAction")@Statelesspublic class LoginAction implements Login { User user; @In public void setUser(User user) {

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

109

Page 115: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

By default, Seam will do a priority search of all contexts, using the name of the property or instancevariable that is being injected. You may wish to specify the context variable name explicitly, using, forexample, @In("currentUser").

If you want Seam to create an instance of the component when there is no existing componentinstance bound to the named context variable, you should specify @In(create=true). If the value isoptional (it can be null), specify @In(required=false).

For some components, it can be repetitive to have to specify @In(create=true) everywhere theyare used. In such cases, you can annotate the component @AutoCreate, and then it will always becreated, whenever needed, even without the explicit use of create=true.

You can even inject the value of an expression:

Injected values are disinjected (for instance, set to null) immediately after method completion andbeing retrived by a user.

(There is much more information about component lifecycle and injection in the next chapter.)

The @Out annotation specifies that an attribute should be withdrawn, either from an instance variable:

or from a getter method:

this.user=user; } ... }

@Name("loginAction")@Statelesspublic class LoginAction implements Login { @In("#{user.username}") String username; ... }

@Name("loginAction")@Statelesspublic class LoginAction implements Login { @Out User user; ... }

@Name("loginAction")@Statelesspublic class LoginAction implements Login { User user; @Out public User getUser() { return user; } ... }

Seam 2 Reference Guide

110

Page 116: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

An attribute may be both injected and retrieved:

or:

5.4. LIFECYCLE METHODS

Session bean and entity bean Seam components support all the usual EJB 3.0 lifecycle callback(@PostConstruct, @PreDestroy, etc). But Seam also supports the use of any of these callbacks withJavaBean components. However, since these annotations are not available in a J2EE environment,Seam defines two additional component lifecycle callbacks, equivalent to @PostConstruct and @PreDestroy.

The @Create method is called after Seam instantiates a component. Components may define only one @Create method.

The @Destroy method is called when the context that the Seam component is bound to, ends.Components may define only one @Destroy method.

In addition, stateful session bean components must define a method with no parameters annotated @Remove. This method is called by Seam when the context ends.

Finally, a related annotation is the @Startup annotation, which may be applied to any application orsession scoped component. The @Startup annotation tells Seam to instantiate the componentimmediately, when the context begins, instead of waiting until it is first referenced by a client. It ispossible to control the order of instantiation of startup components by specifying @Startup(depends={....}).

@Name("loginAction")@Statelesspublic class LoginAction implements Login { @In @Out User user; ... }

@Name("loginAction")@Statelesspublic class LoginAction implements Login { User user; @In public void setUser(User user) { this.user=user; } @Out public User getUser() { return user; } ... }

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

111

Page 117: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

5.5. CONDITIONAL INSTALLATION

The @Install annotation lets you control conditional installation of components that are required insome deployment scenarios and not in others. This is useful if:

You want to mock out some infrastructural component in tests.

You wish to change the implementation of a component in certain deployment scenarios.

You wish to install some components only if their dependencies are available (useful forframework authors).

@Install works by letting you specify precedence and dependencies.

The precedence of a component is a number that Seam uses to decide which component to installwhen there are multiple classes with the same component name in the classpath. Seam will choose thecomponent with the higher precedence. There are some predefined precedence values (in ascendingorder):

1. BUILT_IN — the lowest precedence components are the components built in to Seam.

2. FRAMEWORK — components defined by third-party frameworks may override built-incomponents, but are overridden by application components.

3. APPLICATION — the default precedence. This is appropriate for most application components.

4. DEPLOYMENT — for application components which are deployment-specific.

5. MOCK — for mock objects used in testing.

Suppose we have a component named messageSender that talks to a JMS queue.

In our unit tests, we don't have a JMS queue available, so we would like to remove this method. We willcreate a mock component that exists in the classpath when unit tests are running, but is neverdeployed with the application:

The precedence helps Seam decide which version to use when it finds both components in theclasspath.

This is advantageous if we are able to control exactly which classes are in the classpath. But if you are

@Name("messageSender") public class MessageSender { public void sendMessage() { //do something with JMS }}

@Name("messageSender") @Install(precedence=MOCK)public class MockMessageSender extends MessageSender { public void sendMessage() { //do nothing! }}

Seam 2 Reference Guide

112

Page 118: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

writing a reusable framework with many dependencies, you don't want to have to break thatframework across many jars. The answer would be to be able to decide which components to installdepending upon what other components are installed, and upon what classes are available in theclasspath. The @Install annotation also controls this functionality. Seam uses this mechanisminternally to enable conditional installation of many of the built-in components. However, you probablywon't need to use it in your application.

5.6. LOGGING

An example of generic logging code:

Seam provides a logging API that simplifies this code significantly:

It doesn't matter if you declare the log variable static or not; it will work either way, except for entitybean components which require the log variable to be static.

NOTE

The if ( log.isDebugEnabled() ) guard is no longer necessary, since stringconcatenation happens inside the debug() method. Also the log category does notusually require specification since Seam knows what component it is injecting the Loginto.

If User and Product are Seam components available in the current contexts, it gets even better:

private static final Log log = LogFactory.getLog(CreateOrderAction.class); public Order createOrder(User user, Product product, int quantity) { if ( log.isDebugEnabled() ) { log.debug("Creating new order for user: " + user.username() + " product: " + product.name() + " quantity: " + quantity); } return new Order(user, product, quantity);}

@Logger private Log log; public Order createOrder(User user, Product product, int quantity) { log.debug("Creating new order for user: #0 product: #1 quantity: #2", user.username(), product.name(), quantity); return new Order(user, product, quantity);}

@Logger private Log log; public Order createOrder(User user, Product product, int quantity) { log.debug("Creating new order for user: #{user.username} product: #{product.name} quantity: #0", quantity); return new Order(user, product, quantity);}

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

113

Page 119: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam logging decides whether to send output to log4j or JDK logging. If log4j is in the classpath, Seamwith use it. If it is not, Seam will use JDK logging.

5.7. THE MUTABLE INTERFACE AND @READONLY

Many application servers feature an amazingly broken implementation of HttpSession clustering,where changes to the state of mutable objects bound to the session are only replicated when theapplication calls setAttribute() explicitly. This is a source of bugs that can not effectively be testedfor at development time, since they will only manifest when failover occurs. Furthermore, the actualreplication message contains the entire serialized object graph bound to the session attribute, which isinefficient.

EJB stateful session beans must perform automatic checking and replication of mutable state and asophisticated EJB container can introduce optimizations such as attribute-level replication.Unfortunately, not all Seam users have the good fortune to be working in an environment that supportsEJB 3.0. So, for session and conversation scoped JavaBean and entity bean components, Seamprovides an extra layer of cluster-safe state management over the top of the web container sessionclustering.

For session or conversation scoped JavaBean components, Seam automatically forces replication tooccur by calling setAttribute() once in every request that the component was invoked by theapplication. Of course, this strategy is inefficient for some read components. You can control thisbehavior by implementing the org.jboss.seam.core.Mutable interface, or by extending org.jboss.seam.core.AbstractMutable, and writing your own dirty-checking logic inside thecomponent. For example,

Or, you can use the @ReadOnly annotation to achieve a similar effect:

@Name("account")public class Account extends AbstractMutable{ private BigDecimal balance; public void setBalance(BigDecimal balance) { setDirty(this.balance, balance); this.balance = balance; } public BigDecimal getBalance() { return balance; } ... }

@Name("account")public class Account{ private BigDecimal balance; public void setBalance(BigDecimal balance) {

Seam 2 Reference Guide

114

Page 120: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

For session or conversation scoped entity bean components, Seam automatically forces replication tooccur by calling setAttribute() once in every request, unless the (conversation-scoped) entity iscurrently associated with a Seam-managed persistence context, in which case no replication is needed. Thisstrategy is not necessarily efficient, so session or conversation scope entity beans should be used withcare. You can always write a stateful session bean or JavaBean component to manage the entity beaninstance. For example,

NOTE

The EntityHome class in the Seam Application Framework provides a great example ofmanaging an entity bean instance using a Seam component.

5.8. FACTORY AND MANAGER COMPONENTS

We often need to work with objects that are not Seam components. But we still want to be able to injectthem into our components using @In and use them in value and method binding expressions, etc.Sometimes, we even need to tie them into the Seam context lifecycle (@Destroy, for example). So theSeam contexts can contain objects which are not Seam components, and Seam provides a couple ofnice features that make it easier to work with non-component objects bound to contexts.

The factory component pattern lets a Seam component act as the instigator for a non-componentobject. A factory method will be called when a context variable is referenced but has no value bound toit. We define factory methods using the @Factory annotation. The factory method binds a value to thecontext variable, and determines the scope of the bound value. There are two styles of factory method.The first style returns a value, which is bound to the context by Seam:

this.balance = balance; } @ReadOnly public BigDecimal getBalance() { return balance; } ... }

@Stateful@Name("account")public class AccountManager extends AbstractMutable{ private Account account; // an entity bean @Unwrap public void getAccount() { return account; } ... }

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

115

Page 121: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The second style is a method of type void which binds the value to the context variable itself:

In both cases, the factory method is called when we reference the customerList context variableand its value is null, and then has no further part to play in the lifecycle of the value. An even morepowerful pattern is the manager component pattern. In this case, we have a Seam component that isbound to a context variable, that manages the value of the context variable, while remaining invisible toclients.

A manager component is any component with an @Unwrap method. This method returns the value thatwill be visible to clients, and is called every time a context variable is referenced.

The manager component pattern is especially useful if we have an object where you need more controlover the lifecycle of the component. For example, if you have a heavyweight object that needs acleanup operation when the context ends you could @Unwrap the object, and perform cleanup in the @Destroy method of the manager component.

@Factory(scope=CONVERSATION)public List<Customer> getCustomerList() { return ... ;}

@DataModel List<Customer> customerList;

@Factory("customerList")public void initCustomerList() { customerList = ... ;}

@Name("customerList")@Scope(CONVERSATION)public class CustomerListManager{ ... @Unwrap public List<Customer> getCustomerList() { return ... ; }}

@Name("hens")@Scope(APPLICATION) public class HenHouse { Set<Hen> hens; @In(required=false) Hen hen; @Unwrap public List<Hen> getHens() { if (hens == null) { // Setup our hens } return hens;

Seam 2 Reference Guide

116

Page 122: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Here the managed component observes many events which change the underlying object. Thecomponent manages these actions itself, and because the object is unwrapped on every access, aconsistent view is provided.

} @Observer({"chickBorn", "chickenBoughtAtMarket"}) public addHen() { hens.add(hen); } @Observer("chickenSoldAtMarket") public removeHen() { hens.remove(hen); } @Observer("foxGetsIn") public removeAllHens() { hens.clear(); } ...}

CHAPTER 5. THE CONTEXTUAL COMPONENT MODEL

117

Page 123: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 6. CONFIGURING SEAM COMPONENTSThe philosophy of minimizing XML-based configuration is extremely strong in Seam. Nevertheless,there are various reasons why we might want to configure a Seam component using XML: to isolatedeployment-specific information from the Java code, to enable the creation of re-usable frameworks,to configure Seam's built-in functionality, etc. Seam provides two basic approaches to configuringcomponents: configuration via property settings in a properties file or in web.xml, and configurationvia components.xml.

6.1. CONFIGURING COMPONENTS VIA PROPERTY SETTINGS

Seam components may be provided with configuration properties either via servlet contextparameters, or via a properties file named seam.properties in the root of the classpath.

The configurable Seam component must expose JavaBeans-style property setter methods for theconfigurable attributes. If a Seam component named com.jboss.myapp.settings has a settermethod named setLocale(), we can provide a property named com.jboss.myapp.settings.locale in the seam.properties file or as a servlet contextparameter, and Seam will set the value of the locale attribute whenever it instantiates thecomponent.

The same mechanism is used to configure Seam itself. For example, to set the conversation timeout,we provide a value for org.jboss.seam.core.manager.conversationTimeout in web.xml or seam.properties. (There is a built-in Seam component named org.jboss.seam.core.managerwith a setter method named setConversationTimeout().)

6.2. CONFIGURING COMPONENTS VIA COMPONENTS.XML

The components.xml file is a bit more powerful than property settings. It lets you:

Configure components that have been installed automatically—including both built-incomponents, and application components that have been annotated with the @Nameannotation and picked up by Seam's deployment scanner.

Install classes with no @Name annotation as Seam components—this is most useful for certainkinds of infrastructural components which can be installed multiple times different names (forexample Seam-managed persistence contexts).

Install components that do have a @Name annotation but are not installed by default because ofan @Install annotation that indicates the component should not be installed.

Override the scope of a component.

A components.xml file may appear in one of three different places:

The WEB-INF directory of a war.

The META-INF directory of a jar.

Any directory of a jar that contains classes with an @Name annotation.

Usually, Seam components are installed when the deployment scanner discovers a class with a @Nameannotation sitting in an archive with a seam.properties file or a META-INF/components.xml file.(Unless the component has an @Install annotation indicating it should not be installed by default.)

Seam 2 Reference Guide

118

Page 124: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The components.xml file lets us handle special cases where we need to override the annotations.

For example, the following components.xml file installs jBPM:

This example does the same thing:

This one installs and configures two different Seam-managed persistence contexts:

As does this one:

This example creates a session-scoped Seam-managed persistence context (this is not recommendedin practice):

<components xmlns="http://jboss.com/products/seam/components" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpm="http://jboss.com/products/seam/bpm"> <bpm:jbpm/></components>

<components> <component class="org.jboss.seam.bpm.Jbpm"/></components>

<components xmlns="http://jboss.com/products/seam/components" xmlns:persistence="http://jboss.com/products/seam/persistence"

<persistence:managed-persistence-context name="customerDatabase" persistence-unit-jndi-name="java:/customerEntityManagerFactory"/> <persistence:managed-persistence-context name="accountingDatabase" persistence-unit-jndi-name="java:/accountingEntityManagerFactory"/>

</components>

<components> <component name="customerDatabase" class="org.jboss.seam.persistence.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/customerEntityManagerFactory</property> </component> <component name="accountingDatabase" class="org.jboss.seam.persistence.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/accountingEntityManagerFactory</property> </component></components>

CHAPTER 6. CONFIGURING SEAM COMPONENTS

119

Page 125: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

It is common to use the auto-create option for infrastructural objects like persistence contexts,which saves you from having to explicitly specify create=true when you use the @In annotation.

The <factory> declaration lets you specify a value or method binding expression that will beevaluated to initialize the value of a context variable when it is first referenced.

<components xmlns="http://jboss.com/products/seam/components" xmlns:persistence="http://jboss.com/products/seam/persistence"

<persistence:managed-persistence-context name="productDatabase" scope="session" persistence-unit-jndi-name="java:/productEntityManagerFactory"/>

</components>

<components> <component name="productDatabase" scope="session" class="org.jboss.seam.persistence.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/productEntityManagerFactory</property> </component>

</components>

<components xmlns="http://jboss.com/products/seam/components" xmlns:persistence="http://jboss.com/products/seam/persistence"

<persistence:managed-persistence-context name="productDatabase" auto-create="true" persistence-unit-jndi-name="java:/productEntityManagerFactory"/>

</components>

<components> <component name="productDatabase" auto-create="true" class="org.jboss.seam.persistence.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/productEntityManagerFactory</property> </component>

</components>

<components>

Seam 2 Reference Guide

120

Page 126: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

You can create an "alias" (a second name) for a Seam component like so:

You can even create an "alias" for a commonly used expression:

It is especially common to see the use of auto-create="true" with the <factory> declaration:

Sometimes we want to reuse the same components.xml file with minor changes during bothdeployment and testing. Seam lets you place wildcards of the form @wildcard@ in the components.xml file which can be replaced either by your Ant build script (at deployment time) or byproviding a file named components.properties in the classpath (at development time). You'll seethis approach used in the Seam examples.

6.3. FINE-GRAINED CONFIGURATION FILES

If you have a large number of components that need to be configured in XML, it makes much moresense to split up the information in components.xml into many small files. Seam lets you putconfiguration for a class named, for example, com.helloworld.Hello in a resource named com/helloworld/Hello.component.xml. (You might be familiar with this pattern, since it is thesame one we use in Hibernate.) The root element of the file may be either a <components> or <component> element.

The first option lets you define multiple components in the file:

<factory name="contact" method="#{contactManager.loadContact}" scope="CONVERSATION"/>

</components>

<components>

<factory name="user" value="#{actor}" scope="STATELESS"/>

</components>

<components>

<factory name="contact" value="#{contactManager.contact}" scope="STATELESS"/>

</components>

<components>

<factory name="session" value="#{entityManager.delegate}" scope="STATELESS" auto-create="true"/>

</components>

<components> <component class="com.helloworld.Hello" name="hello"> <property name="name">#{user.name}</property>

CHAPTER 6. CONFIGURING SEAM COMPONENTS

121

Page 127: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The second option only lets you define or configure one component, but is less noisy:

In the second option, the class name is implied by the file in which the component definition appears.

Alternatively, you may put configuration for all classes in the com.helloworld package in com/helloworld/components.xml.

6.4. CONFIGURABLE PROPERTY TYPES

Properties of string, primitive or primitive wrapper type may be configured just as you would expect:

Arrays, sets and lists of strings or primitives are also supported:

Even maps with String-valued keys and string or primitive values are supported:

</component> <factory name="message" value="#{hello.message}"/></components>

<component name="hello"> <property name="name">#{user.name}</property></component>

org.jboss.seam.core.manager.conversationTimeout 60000

<core:manager conversation-timeout="60000"/>

<component name="org.jboss.seam.core.manager"> <property name="conversationTimeout">60000</property></component>

org.jboss.seam.bpm.jbpm.processDefinitions order.jpdl.xml, return.jpdl.xml, inventory.jpdl.xml

<bpm:jbpm> <bpm:process-definitions> <value>order.jpdl.xml</value> <value>return.jpdl.xml</value> <value>inventory.jpdl.xml</value> </bpm:process-definitions></bpm:jbpm>

<component name="org.jboss.seam.bpm.jbpm"> <property name="processDefinitions"> <value>order.jpdl.xml</value> <value>return.jpdl.xml</value> <value>inventory.jpdl.xml</value> </property></component>

<component name="issueEditor"> <property name="issueStatuses">

Seam 2 Reference Guide

122

Page 128: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Finally, you may wire together components using a value-binding expression. Note that this is quitedifferent to injection using @In, since it happens at component instantiation time instead of invocationtime. It is therefore much more similar to the dependency injection facilities offered by traditional IoCcontainers like JSF or Spring.

6.5. USING XML NAMESPACES

Throughout the examples, there have been two competing ways of declaring components: with andwithout the use of XML namespaces. The following shows a typical components.xml file withoutnamespaces:

As you can see, this is somewhat verbose. Even worse, the component and attribute names cannot bevalidated at development time.

The namespaced version looks like this:

<key>open</key> <value>open issue</value> <key>resolved</key> <value>issue resolved by developer</value> <key>closed</key> <value>resolution accepted by user</value> </property></component>

<drools:managed-working-memory name="policyPricingWorkingMemory" rule-base="#{policyPricingRules}"/>

<component name="policyPricingWorkingMemory" class="org.jboss.seam.drools.ManagedWorkingMemory"> <property name="ruleBase">#{policyPricingRules}</property></component>

<?xml version="1.0" encoding="UTF-8"?><components xmlns="http://jboss.com/products/seam/components" xsi:schemaLocation="http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd">

<component class="org.jboss.seam.core.init"> <property name="debug">true</property> <property name="jndiPattern">@jndiPattern@</property> </component> </components>

<?xml version="1.0" encoding="UTF-8"?><components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.1.xsd http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd">

CHAPTER 6. CONFIGURING SEAM COMPONENTS

123

Page 129: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Even though the schema declarations are verbose, the actual XML content is lean and easy tounderstand. The schemas provide detailed information about each component and the attributesavailable, allowing XML editors to offer intelligent autocomplete. The use of namespaced elementsmakes generating and maintaining correct components.xml files much simpler.

Now, this works great for the built-in Seam components, but what about user components? There aretwo options. First, Seam supports mixing the two models, allowing the use of the generic <component> declarations for user components, along with namespaced declarations for built-incomponents. But even better, Seam allows you to quickly declare namespaces for your owncomponents.

Any Java package can be associated with an XML namespace by annotating the package with the @Namespace annotation. (Package-level annotations are declared in a file named package-info.java in the package directory.) Here is an example from the seampay demo:

That is all you need to do to use the namespaced style in components.xml! Now we can write:

Or:

<core:init debug="true" jndi-pattern="@jndiPattern@"/>

</components>

@Namespace(value="http://jboss.com/products/seam/examples/seampay")package org.jboss.seam.example.seampay;

import org.jboss.seam.annotations.Namespace;

<components xmlns="http://jboss.com/products/seam/components" xmlns:pay="http://jboss.com/products/seam/examples/seampay" ... >

<pay:payment-home new-instance="#{newPayment}" created-message="Created a new payment to #{newPayment.payee}" />

<pay:payment name="newPayment" payee="Somebody" account="#{selectedAccount}" payment-date="#{currentDatetime}" created-date="#{currentDatetime}" /> ...</components>

<components xmlns="http://jboss.com/products/seam/components" xmlns:pay="http://jboss.com/products/seam/examples/seampay" ... >

<pay:payment-home> <pay:new-instance>"#{newPayment}"</pay:new-instance> <pay:created-message>Created a new payment to #{newPayment.payee}</pay:created-message> </pay:payment-home> <pay:payment name="newPayment">

Seam 2 Reference Guide

124

Page 130: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

These examples illustrate the two usage models of a namespaced element. In the first declaration, the <pay:payment-home> references the paymentHome component:

The element name is the hyphenated form of the component name. The attributes of the element arethe hyphenated form of the property names.

In the second declaration, the <pay:payment> element refers to the Payment class in the org.jboss.seam.example.seampay package. In this case Payment is an entity that is beingdeclared as a Seam component:

If we want validation and autocompletion to work for user-defined components, we will need a schema.Seam does not yet provide a mechanism to automatically generate a schema for a set of components,so it is necessary to generate one manually. The schema definitions for the standard Seam packagescan be used for guidance.

The following are the the namespaces used by Seam:

components — http://jboss.com/products/seam/components

core — http://jboss.com/products/seam/core

drools — http://jboss.com/products/seam/drools

framework — http://jboss.com/products/seam/framework

jms — http://jboss.com/products/seam/jms

remoting — http://jboss.com/products/seam/remoting

<pay:payee>Somebody"</pay:payee> <pay:account>#{selectedAccount}</pay:account> <pay:payment-date>#{currentDatetime}</pay:payment-date> <pay:created-date>#{currentDatetime}</pay:created-date> </pay:payment> ...</components>

package org.jboss.seam.example.seampay;...@Name("paymentHome")public class PaymentController extends EntityHome<Payment>{ ... }

package org.jboss.seam.example.seampay;...@Entitypublic class Payment implements Serializable{ ...}

CHAPTER 6. CONFIGURING SEAM COMPONENTS

125

Page 131: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

theme — http://jboss.com/products/seam/theme

security — http://jboss.com/products/seam/security

mail — http://jboss.com/products/seam/mail

web — http://jboss.com/products/seam/web

pdf — http://jboss.com/products/seam/pdf

spring — http://jboss.com/products/seam/spring

Seam 2 Reference Guide

126

Page 132: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTIONHANDLINGComplementing the contextual component model, there are two further basic concepts that facilitatethe extreme loose-coupling that is the distinctive feature of Seam applications. The first is a strongevent model where events may be mapped to event listeners via JSF-like method binding expressions.The second is the pervasive use of annotations and interceptors to apply cross-cutting concerns tocomponents which implement business logic.

7.1. SEAM EVENTS

The Seam component model was developed for use with event-driven applications , specifically toenable the development of fine-grained, loosely-coupled components in a fine-grained eventing model.Events in Seam come in several types, most of which we have already seen:

JSF events

jBPM transition events

Seam page actions

Seam component-driven events

Seam contextual events

All of these various kinds of events are mapped to Seam components via JSF EL method bindingexpressions. For a JSF event, this is defined in the JSF template:

For a jBPM transition event, it is specified in the jBPM process definition or pageflow definition:

You can find out more information about JSF events and jBPM events throughout the rest of thedocumentation. For now we will concentrate upon the two additional types of events defined by Seam.

7.2. PAGE ACTIONS

A Seam page action is an event that occurs just before we render a page. We declare page actions in WEB-INF/pages.xml and define them for either a particular JSF view id:

Or we can use a * wildcard as a suffix to the view-id to specify an action that applies to all view idsthat match the pattern:

<h:commandButton value="Click me!" action="#{helloWorld.sayHello}"/>

<start-page name="hello" view-id="/hello.jsp"> <transition to="hello"> <action expression="#{helloWorld.sayHello}"/> </transition></start-page>

<pages> <page view-id="/hello.jsp" action="#{helloWorld.sayHello}"/></pages>

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

127

Page 133: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If multiple wildcarded page actions match the current view-id, Seam will call all the actions, in orderof least-specific to most-specific.

The page action method can return a JSF outcome. If the outcome is non-null, Seam will use thedefined navigation rules to navigate to a view.

Furthermore, the view-id mentioned in the <page> element need not correspond to a real JSP orFacelets page! So, we can reproduce the functionality of a traditional action-oriented framework likeStruts or WebWork using page actions. For example:

This is quite useful if you want to do complex things in response to non-faces requests (for example,HTTP GET requests).

Multiple or conditional page actions my be specified using the <action> tag:

7.3. PAGE PARAMETERS

A JSF faces request (a form submission) encapsulates both an action (a method binding) andparameters (input value bindings). A page action might also require parameters.

Since GET requests are bookmarkable, page parameters are passed as human-readable requestparameters.

You can use page parameters with or without an action method.

7.3.1. Mapping request parameters to the model

Seam lets us provide a value binding that maps a named request parameter to an attribute of a modelobject.

The <param> declaration is bidirectional, just like a value binding for a JSF input:

<pages> <page view-id="/hello/*" action="#{helloWorld.sayHello}"/></pages>

TODO: translate struts action into page action

<pages> <page view-id="/hello.jsp"> <action execute="#{helloWorld.sayHello}" if="#{not validation.failed}"/> <action execute="#{hitCount.increment}"/> </page></pages>

<pages> <page view-id="/hello.jsp" action="#{helloWorld.sayHello}"> <param name="firstName" value="#{person.firstName}"/> <param name="lastName" value="#{person.lastName}"/> </page> </pages>

Seam 2 Reference Guide

128

Page 134: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

When a non-faces (GET) request for the view id occurs, Seam sets the value of the namedrequest parameter onto the model object, after performing appropriate type conversions.

Any <s:link> or <s:button> transparently includes the request parameter. The value ofthe parameter is determined by evaluating the value binding during the render phase (whenthe <s:link> is rendered).

Any navigation rule with a <redirect/> to the view id transparently includes the requestparameter. The value of the parameter is determined by evaluating the value binding at theend of the invoke application phase.

The value is transparently propagated with any JSF form submission for the page with thegiven view id. This means that view parameters behave like PAGE-scoped context variables forfaces requests.

The essential idea behind all this is that however we get from any other page to /hello.jsp (or from /hello.jsp back to /hello.jsp), the value of the model attribute referred to in the value binding isremembered, without the need for a conversation (or other server-side state).

7.4. PROPAGATING REQUEST PARAMETERS

If just the name attribute is specified then the request parameter is propagated using the PAGE context(it isn't mapped to model property).

Propagation of page parameters is especially useful if you want to build multi-layer master-detailCRUD pages. You can use it to remember which view you were previously on (e.g. when pressing the Save button), and which entity you were editing.

Any <s:link> or <s:button> transparently propagates the request parameter if thatparameter is listed as a page parameter for the view.

The value is transparently propagated with any JSF form submission for the page with thegiven view id. (This means that view parameters behave like PAGE-scoped context variables forfaces requests.

This all sounds rather complex, and you are probably wondering if such an exotic construct is reallyworth the effort. Actually, the idea is very natural once the thought behind it becomes apparent; it isdefinitely worth taking the time to understand. Page parameters are the most elegant way topropagate state across a non-faces request. They are especially useful for problems like searchscreens with bookmarkable results pages, where we would like to be able to write our application codeto handle both POST and GET requests with the same code. Page parameters eliminate repetitivelisting of request parameters in the view definition and make redirects much easier to code.

7.5. CONVERSION AND VALIDATION

You can specify a JSF converter for complex model propreties:

<pages> <page view-id="/hello.jsp" action="#{helloWorld.sayHello}"> <param name="firstName" /> <param name="lastName" /> </page> </pages>

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

129

Page 135: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Alternatively:

JSF validators, and required="true" may also be used:

Alternatively:

Even better, model-based Hibernate validator annotations are automatically recognized and validated.

When type conversion or validation fails, a global FacesMessage is added to the FacesContext.

7.6. NAVIGATION

You can use standard JSF navigation rules defined in faces-config.xml in a Seam application.However, JSF navigation rules have a number of annoying limitations:

It is not possible to specify request parameters to be used when redirecting.

It is not possible to begin or end conversations from a rule.

<pages> <page view-id="/calculator.jsp" action="#{calculator.calculate}"> <param name="x" value="#{calculator.lhs}"/> <param name="y" value="#{calculator.rhs}"/> <param name="op" converterId="com.my.calculator.OperatorConverter" value="#{calculator.op}"/> </page></pages>

<pages> <page view-id="/calculator.jsp" action="#{calculator.calculate}"> <param name="x" value="#{calculator.lhs}"/> <param name="y" value="#{calculator.rhs}"/> <param name="op" converter="#{operatorConverter}" value="#{calculator.op}"/> </page></pages>

<pages> <page view-id="/blog.xhtml"> <param name="date" value="#{blog.date}" validatorId="com.my.blog.PastDate" required="true"/> </page></pages>

<pages> <page view-id="/blog.xhtml"> <param name="date" value="#{blog.date}" validator="#{pastDateValidator}" required="true"/> </page></pages>

Seam 2 Reference Guide

130

Page 136: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Rules work by evaluating the return value of the action method; it is not possible to evaluate anarbitrary EL expression.

A further problem is that "orchestration" logic gets scattered between pages.xml and faces-config.xml. It's better to unify this logic into pages.xml.

This JSF navigation rule:

Can be rewritten as follows:

But it would be even nicer if we didn't have to pollute our DocumentEditor component with string-valued return values (the JSF outcomes). So Seam lets us write:

Or even:

<navigation-rule> <from-view-id>/editDocument.xhtml</from-view-id> <navigation-case> <from-action>#{documentEditor.update}</from-action> <from-outcome>success</from-outcome> <to-view-id>/viewDocument.xhtml</to-view-id> <redirect/> </navigation-case> </navigation-rule>

<page view-id="/editDocument.xhtml"> <navigation from-action="#{documentEditor.update}"> <rule if-outcome="success"> <redirect view-id="/viewDocument.xhtml"/> </rule> </navigation> </page>

<page view-id="/editDocument.xhtml"> <navigation from-action="#{documentEditor.update}" evaluate="#{documentEditor.errors.size}"> <rule if-outcome="0"> <redirect view-id="/viewDocument.xhtml"/> </rule> </navigation> </page>

<page view-id="/editDocument.xhtml"> <navigation from-action="#{documentEditor.update}"> <rule if="#{documentEditor.errors.empty}"> <redirect view-id="/viewDocument.xhtml"/> </rule>

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

131

Page 137: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The first form evaluates a value binding to determine the outcome value to be used by the subsequentrules. The second approach ignores the outcome and evaluates a value binding for each possible rule.

Of course, when an update succeeds, we probably want to end the current conversation. We can dothat like this:

Since we have ended the conversation, any subsequent requests will not know which document we areinterested in. We can pass the document ID as a request parameter which also makes the viewbookmarkable:

Null outcomes are a special case in JSF. The null outcome is interpreted to mean redisplay the page.The following navigation rule matches any non-null outcome, but not the null outcome:

If you want to perform navigation when a null outcome occurs, use the following form instead:

</navigation> </page>

<page view-id="/editDocument.xhtml"> <navigation from-action="#{documentEditor.update}"> <rule if="#{documentEditor.errors.empty}"> <end-conversation/> <redirect view-id="/viewDocument.xhtml"/> </rule> </navigation> </page>

<page view-id="/editDocument.xhtml"> <navigation from-action="#{documentEditor.update}"> <rule if="#{documentEditor.errors.empty}"> <end-conversation/> <redirect view-id="/viewDocument.xhtml"> <param name="documentId" value="#{documentEditor.documentId}"/> </redirect> </rule> </navigation> </page>

<page view-id="/editDocument.xhtml"> <navigation from-action="#{documentEditor.update}"> <rule> <render view-id="/viewDocument.xhtml"/> </rule> </navigation> </page>

<page view-id="/editDocument.xhtml">

Seam 2 Reference Guide

132

Page 138: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The view-id may be given as a JSF EL expression:

7.7. FINE-GRAINED FILES FOR DEFINITION OF NAVIGATION, PAGEACTIONS AND PARAMETERS

If you have a lot of different page actions and page parameters, or even just a lot of navigation rules,you will almost certainly want to split the declarations up over multiple files. You can define actionsand parameters for a page with the view-id /calc/calculator.jsp in a resource named calc/calculator.page.xml. The root element in this case is the <page> element, and the view-id is implied:

7.8. COMPONENT-DRIVEN EVENTS

Seam components can interact by simply calling each others methods. Stateful components may evenimplement the observer/observable pattern. However to enable components to interact in a moreloosely-coupled fashion than is possible when the components call each others methods directly, Seamprovides component-driven events.

We specify event listeners (observers) in components.xml.

Where the event type is just an arbitrary string.

<navigation from-action="#{documentEditor.update}"> <render view-id="/viewDocument.xhtml"/> </navigation> </page>

<page view-id="/editDocument.xhtml">

<navigation> <rule if-outcome="success"> <redirect view-id="/#{userAgent}/displayDocument.xhtml"/> </rule> </navigation> </page>

<page action="#{calculator.calculate}"> <param name="x" value="#{calculator.lhs}"/> <param name="y" value="#{calculator.rhs}"/> <param name="op" converter="#{operatorConverter}" value="#{calculator.op}"/></page>

<components> <event type="hello"> <action execute="#{helloListener.sayHelloBack}"/> <action execute="#{logger.logHello}"/> </event></components>

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

133

Page 139: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

When an event occurs, the actions registered for that event will be called in the order they appear in components.xml. How does a component raise an event? Seam provides a built-in component forthis.

Or you can use an annotation.

Notice that this event producer has no dependency upon event consumers. The event listener maynow be implemented with absolutely no dependency upon the producer:

The method binding defined in components.xml above takes care of mapping the event to theconsumer. If you don't like futzing about in the components.xml file, you can use an annotationinstead:

You might wonder why event objects have not been mentioned. In Seam, there is no need for an eventobject to propagate state between event producer and listener. State is held in the Seam contexts, andis shared between components. However, if you wish to pass an event object, you can:

@Name("helloWorld")public class HelloWorld { public void sayHello() { FacesMessages.instance().add("Hello World!"); Events.instance().raiseEvent("hello"); }}

@Name("helloWorld")public class HelloWorld { @RaiseEvent("hello") public void sayHello() { FacesMessages.instance().add("Hello World!"); }}

@Name("helloListener")public class HelloListener { public void sayHelloBack() { FacesMessages.instance().add("Hello to you too!"); }}

@Name("helloListener")public class HelloListener { @Observer("hello") public void sayHelloBack() { FacesMessages.instance().add("Hello to you too!"); }}

@Name("helloWorld")public class HelloWorld { private String name; public void sayHello() { FacesMessages.instance().add("Hello World, my name is #0.", name);

Seam 2 Reference Guide

134

Page 140: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

7.9. CONTEXTUAL EVENTS

Seam defines a number of built-in events that the application can use to perform special kinds offramework integration. The events are:

org.jboss.seam.validationFailed — called when JSF validation fails

org.jboss.seam.noConversation — called when there is no long running conversation anda long running conversation is required

org.jboss.seam.preSetVariable.<name> — called when the context variable <name> isset

org.jboss.seam.postSetVariable.<name> — called when the context variable <name>is set

org.jboss.seam.preRemoveVariable.<name> — called when the context variable<name> is unset

org.jboss.seam.postRemoveVariable.<name> — called when the context variable<name> is unset

org.jboss.seam.preDestroyContext.<SCOPE> — called before the <SCOPE> context isdestroyed

org.jboss.seam.postDestroyContext.<SCOPE> — called after the <SCOPE> context isdestroyed

org.jboss.seam.beginConversation — called whenever a long-running conversationbegins

org.jboss.seam.endConversation — called whenever a long-running conversation ends

org.jboss.seam.conversationTimeout— called when a conversation timeout occurs. Theconversation id is passed as a parameter.

org.jboss.seam.beginPageflow — called when a pageflow begins

org.jboss.seam.beginPageflow.<name> — called when the pageflow <name> begins

org.jboss.seam.endPageflow — called when a pageflow ends

org.jboss.seam.endPageflow.<name> — called when the pageflow <name> ends

Events.instance().raiseEvent("hello", name); }}

@Name("helloListener")public class HelloListener { @Observer("hello") public void sayHelloBack(String name) { FacesMessages.instance().add("Hello #0!", name); }}

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

135

Page 141: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

org.jboss.seam.createProcess.<name> — called when the process <name> is created

org.jboss.seam.endProcess.<name> — called when the process <name> ends

org.jboss.seam.initProcess.<name> — called when the process <name> is associatedwith the conversation

org.jboss.seam.initTask.<name> — called when the task <name> is associated with theconversation

org.jboss.seam.startTask.<name> — called when the task <name> is started

org.jboss.seam.endTask.<name> — called when the task <name> is ended

org.jboss.seam.postCreate.<name> — called when the component <name> is created

org.jboss.seam.preDestroy.<name> — called when the component <name> isdestroyed

org.jboss.seam.beforePhase — called before the start of a JSF phase

org.jboss.seam.afterPhase — called after the end of a JSF phase

org.jboss.seam.postInitialization — called when Seam has initialized and started upall components

org.jboss.seam.security.loggedOut — called when a user logs out

org.jboss.seam.security.loginFailed — called when a user authentication attemptfails

org.jboss.seam.security.loginSuccessful — called when a user is successfullyauthenticated

org.jboss.seam.security.notAuthorized — called when an authorization check fails

org.jboss.seam.postAuthenticate.<name> — called after a user is authenticated

org.jboss.seam.preAuthenticate.<name> — called before attempting to authenticate auser

org.jboss.seam.notLoggedIn — called there is no authenticated user and authenticationis required

org.jboss.seam.exceptionHandled.<type> — called when an uncaught exception ishandled by Seam

org.jboss.seam.exceptionHandled — called when an uncaught exception is handled bySeam

org.jboss.seam.exceptionNotHandled — called when there was no handler for anuncaught exception

org.jboss.seam.afterTransactionSuccess — called when a transaction succeeds in theSeam Application Framework

Seam 2 Reference Guide

136

Page 142: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

org.jboss.seam.afterTransactionSuccess.<name> — called when a transactionsucceeds in the Seam Application Framework which manages an entity called <name>

Seam components may observe any of these events in just the same way they observe any othercomponent-driven events.

7.10. SEAM INTERCEPTORS

EJB 3.0 introduced a standard interceptor model for session bean components. To add an interceptorto a bean, you need to write a class with a method annotated @AroundInvoke and annotate the beanwith an @Interceptors annotation that specifies the name of the interceptor class. For example, thefollowing interceptor checks that the user is logged in before allowing invoking an action listenermethod:

To apply this interceptor to a session bean which acts as an action listener, we must annotate thesession bean @Interceptors(LoggedInInterceptor.class). This is a somewhat uglyannotation. Seam builds upon the interceptor framework in EJB3 by allowing you to use @Interceptors as a meta-annotation for class level interceptors (those annotated @Target(TYPE)). In our example, we would create an @LoggedIn annotation, as follows:

We can now simply annotate our action listener bean with @LoggedIn to apply the interceptor.

public class LoggedInInterceptor {

@AroundInvoke public Object checkLoggedIn(InvocationContext invocation) throws Exception { boolean isLoggedIn = Contexts.getSessionContext().get("loggedIn")!=null; if (isLoggedIn) { //the user is already logged in return invocation.proceed(); } else { //the user is not logged in, fwd to login page return "login"; } }

}

@Target(TYPE)@Retention(RUNTIME)@Interceptors(LoggedInInterceptor.class)public @interface LoggedIn {}

@Stateless@Name("changePasswordAction")@LoggedIn@Interceptors(SeamInterceptor.class)public class ChangePasswordAction implements ChangePassword { ...

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

137

Page 143: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If interceptor ordering is important (it usually is), you can add @Interceptor annotations to yourinterceptor classes to specify a partial order of interceptors.

You can even have a "client-side" interceptor, that runs around any of the built-in functionality of EJB3:

EJB interceptors are stateful, with a lifecycle that is the same as the component they intercept. Forinterceptors which do not need to maintain state, Seam lets you get a performance optimization byspecifying @Interceptor(stateless=true).

Much of the functionality of Seam is implemented as a set of built-in Seam interceptors, including theinterceptors named in the previous example. You don't have to explicitly specify these interceptors byannotating your components; they exist for all interceptable Seam components.

You can even use Seam interceptors with JavaBean components, not just EJB3 beans.

EJB defines interception not only for business methods (using @AroundInvoke), but also for thelifecycle methods @PostConstruct, @PreDestroy, @PrePassivate and @PostActive. Seamsupports all these lifecycle methods on both component and interceptor not only for EJB3 beans, butalso for JavaBean components (except @PreDestroy which is not meaningful for JavaBeancomponents).

7.11. MANAGING EXCEPTIONS

JSF is surprisingly limited when it comes to exception handling. As a partial workaround for thisproblem, Seam lets you define how a particular class of exception is to be treated by annotating theexception class, or declaring the exception class in an XML file. This facility is meant to be combinedwith the EJB 3.0-standard @ApplicationException annotation which specifies whether theexception should cause a transaction rollback.

7.11.1. Exceptions and transactions

EJB specifies well-defined rules that let us control whether an exception immediately marks thecurrent transaction for rollback when it is thrown by a business method of the bean: system exceptionsalways cause a transaction rollback, application exceptions do not cause a rollback by default, but they

public String changePassword() { ... } }

@Interceptor(around={BijectionInterceptor.class, ValidationInterceptor.class, ConversationInterceptor.class}, within=RemoveInterceptor.class)public class LoggedInInterceptor{ ...}

@Interceptor(type=CLIENT)public class LoggedInInterceptor{ ...}

Seam 2 Reference Guide

138

Page 144: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

do if @ApplicationException(rollback=true) is specified. (An application exception is anychecked exception, or any unchecked exception annotated @ApplicationException. A systemexception is any unchecked exception without an @ApplicationException annotation.)

Note that there is a difference between marking a transaction for rollback, and actually rolling it back.The exception rules say that the transaction should be marked rollback only, but it may still be activeafter the exception is thrown.

Seam applies the EJB 3.0 exception rollback rules also to Seam JavaBean components.

But these rules only apply in the Seam component layer. What about an exception that is uncaught andpropagates out of the Seam component layer, and out of the JSF layer? Well, it is always wrong to leavea dangling transaction open, so Seam rolls back any active transaction when an exception occurs andis uncaught in the Seam component layer.

7.11.2. Enabling Seam exception handling

To enable Seam's exception handling, we need to make sure we have the master servlet filter declaredin web.xml:

You may also need to disable Facelets development mode in web.xml and Seam debug mode in components.xml if you want your exception handlers to fire.

7.11.3. Using annotations for exception handling

The following exception results in a HTTP 404 error whenever it propagates out of the Seamcomponent layer. It does not roll back the current transaction immediately when thrown, but thetransaction will be rolled back if it the exception is not caught by another Seam component.

This exception results in a browser redirect whenever it propagates out of the Seam component layer.It also ends the current conversation. It causes an immediate rollback of the current transaction.

Note that @Redirect does not work for exceptions which occur during the render phase of the JSFlifecycle.

You can also use EL to specify the viewId to redirect to.

<filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class></filter>

<filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>*.seam</url-pattern></filter-mapping>

@HttpError(errorCode=404)public class ApplicationException extends Exception { ... }

@Redirect(viewId="/failure.xhtml", end=true)@ApplicationException(rollback=true)public class UnrecoverableApplicationException extends RuntimeException { ... }

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

139

Page 145: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This exception results in a redirect, along with a message to the user, when it propagates out of theSeam component layer. It also immediately rolls back the current transaction.

7.11.4. Using XML for exception handling

Since we can't add annotations to all the exception classes we are interested in, Seam also lets usspecify this functionality in pages.xml.

The last <exception> declaration does not specify a class, and is a catch-all for any exception forwhich handling is not otherwise specified via annotations or in pages.xml.

You can also use EL to specify the view-id to redirect to.

You can also access the handled exception instance through EL, Seam places it in the conversationcontext, for example, to access the message of the exception:

@Redirect(viewId="/error.xhtml", message="Unexpected error")public class SystemException extends RuntimeException { ... }

<pages> <exception class="javax.persistence.EntityNotFoundException"> <http-error error-code="404"/> </exception> <exception class="javax.persistence.PersistenceException"> <end-conversation/> <redirect view-id="/error.xhtml"> <message>Database access failed</message> </redirect> </exception> <exception> <end-conversation/> <redirect view-id="/error.xhtml"> <message>Unexpected failure</message> </redirect> </exception> </pages>

...throw new AuthorizationException("You are not allowed to do this!");

<pages>

<exception class="org.jboss.seam.security.AuthorizationException"> <end-conversation/> <redirect view-id="/error.xhtml"> <message severity="WARN">#{org.jboss.seam.handledException.message}</message> </redirect>

Seam 2 Reference Guide

140

Page 146: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

org.jboss.seam.handledException holds the nested exception that was actually handled by anexception handler. The outermost (wrapper) exception is also available, as org.jboss.seam.exception.

7.11.5. Some common exceptions

If you are using JPA:

If you are using the Seam Application Framework:

If you are using Seam Security:

And, for JSF:

</exception>

</pages>

<exception class="javax.persistence.EntityNotFoundException"> <redirect view-id="/error.xhtml"> <message>Not found</message> </redirect></exception>

<exception class="javax.persistence.OptimisticLockException"> <end-conversation/> <redirect view-id="/error.xhtml"> <message>Another user changed the same data, please try again</message> </redirect></exception>

<exception class="org.jboss.seam.framework.EntityNotFoundException"> <redirect view-id="/error.xhtml"> <message>Not found</message> </redirect></exception>

<exception class="org.jboss.seam.security.AuthorizationException"> <redirect> <message>You don't have permission to do this</message> </redirect></exception> <exception class="org.jboss.seam.security.NotLoggedInException"> <redirect view-id="/login.xhtml"> <message>Please log in first</message> </redirect></exception>

<exception class="javax.faces.application.ViewExpiredException"> <redirect view-id="/error.xhtml"> <message>Your session has timed out, please try again</message>

CHAPTER 7. EVENTS, INTERCEPTORS AND EXCEPTION HANDLING

141

Page 147: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

A ViewExpiredException occurs if the user posts back to a page once their session has expired. no-conversation-view-id and conversation-required give you finer grained control oversession expiration if you are inside a conversation.

</redirect></exception>

Seam 2 Reference Guide

142

Page 148: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 8. CONVERSATIONS AND WORKSPACEMANAGEMENTIt is time to understand Seam's conversation model in more detail.

8.1. SEAM'S CONVERSATION MODEL

The examples we have seen so far make use of a very simple conversation model that follows theserules:

There is always a conversation context active during the apply request values, processvalidations, update model values, invoke application and render response phases of the JSFrequest lifecycle.

At the end of the restore view phase of the JSF request lifecycle, Seam attempts to restoreany previous long-running conversation context. If none exists, Seam creates a new temporaryconversation context.

When an @Begin method is encountered, the temporary conversation context is promoted toa long running conversation.

When an @End method is encountered, any long-running conversation context is demoted to atemporary conversation.

At the end of the render response phase of the JSF request lifecycle, Seam stores the contentsof a long running conversation context or destroys the contents of a temporary conversationcontext.

Any faces request (a JSF postback) will propagate the conversation context. By default, non-faces requests (GET requests, for example) do not propagate the conversation context; seebelow for more information on this.

If the JSF request lifecycle is foreshortened by a redirect, Seam transparently stores andrestores the current conversation context—unless the conversation was already ended via @End(beforeRedirect=true).

Seam transparently propagates the conversation context (including the temporary conversationcontext) across JSF postbacks and redirects. If you do not do anything, a non-faces request (a GETrequest for example) will not propagate the conversation context and will be processed in a newtemporary conversation. This is usually - but not always - the desired behavior.

If you want to propagate a Seam conversation across a non-faces request, you need to explicitly codethe Seam conversation id as a request parameter:

Or, the more JSF-ish:

If you use the Seam tag library, this is equivalent:

<a href="main.jsf?conversationId=#{conversation.id}">Continue</a>

<h:outputLink value="main.jsf"> <f:param name="conversationId" value="#{conversation.id}"/> <h:outputText value="Continue"/></h:outputLink>

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

143

Page 149: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If you wish to disable propagation of the conversation context for a postback, a similar trick is used:

If you use the Seam tag library, this is equivalent:

IMPORTANT

Disabling conversation context propagation is not the same thing as ending theconversation.

The conversationPropagation request parameter, or the <s:conversationPropagation> tagmay even be used to begin and end conversation, or begin a nested conversation.

This conversation model makes it easy to build applications which behave correctly with respect tomulti-window operation. For many applications, this is all that is needed. Some complex applicationshave either or both of the following additional requirements:

A conversation spans many smaller units of user interaction, which execute serially or evenconcurrently. The smaller nested conversations have their own isolated set of conversationstate, and also have access to the state of the outer conversation.

The user is able to switch between many conversations within the same browser window. Thisfeature is called workspace management.

<h:outputLink value="main.jsf"> <s:conversationId/> <h:outputText value="Continue"/></h:outputLink>

<h:commandLink action="main" value="Exit"> <f:param name="conversationPropagation" value="none"/></h:commandLink>

<h:commandLink action="main" value="Exit"> <s:conversationPropagation type="none"/></h:commandLink>

<h:commandLink action="main" value="Exit"> <s:conversationPropagation type="end"/></h:commandLink>

<h:commandLink action="main" value="Select Child"> <s:conversationPropagation type="nested"/></h:commandLink>

<h:commandLink action="main" value="Select Hotel"> <s:conversationPropagation type="begin"/></h:commandLink>

<h:commandLink action="main" value="Select Hotel"> <s:conversationPropagation type="join"/></h:commandLink>

Seam 2 Reference Guide

144

Page 150: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

8.2. NESTED CONVERSATIONS

A nested conversation is created by invoking a method marked @Begin(nested=true) inside thescope of an existing conversation. A nested conversation has its own conversation context, and alsohas read-only access to the context of the outer conversation. (It can read the outer conversation'scontext variables, but not write to them.) When an @End is subsequently encountered, the nestedconversation will be destroyed, and the outer conversation will resume, by popping the conversationstack. Conversations may be nested to any arbitrary depth.

Certain user activity (workspace management, or the back button) can cause the outer conversation tobe resumed before the inner conversation is ended. In this case it is possible to have multipleconcurrent nested conversations belonging to the same outer conversation. If the outer conversationends before a nested conversation ends, Seam destroys all nested conversation contexts along withthe outer context.

A conversation may be thought of as a continuable state. Nested conversations allow the application tocapture a consistent continuable state at various points in a user interaction, thus insuring trulycorrect behavior in the face of backbuttoning and workspace management.

Usually, if a component exists in a parent conversation of the current nested conversation, the nestedconversation will use the same instance. Occasionally, it is useful to have a different instance in eachnested conversation, so that the component instance that exists in the parent conversation is invisibleto its child conversations. You can achieve this behavior by annotating the component @PerNestedConversation.

8.3. STARTING CONVERSATIONS WITH GET REQUESTS

JSF does not define any kind of action listener that is triggered when a page is accessed via a non-facesrequest (for example, a HTTP GET request). This can occur if the user bookmarks the page, or if wenavigate to the page via an <h:outputLink>.

Sometimes we want to begin a conversation immediately the page is accessed. Since there is no JSFaction method, we cannot solve the problem in the usual way, by annotating the action with @Begin.

A further problem arises if the page needs some state to be fetched into a context variable. We havealready seen two ways to solve this problem. If that state is held in a Seam component, we can fetchthe state in a @Create method. If not, we can define a @Factory method for the context variable.

If none of these options works for you, Seam lets you define a page action in the pages.xml file.

This action method is called at the beginning of the render response phase, any time the page is aboutto be rendered. If a page action returns a non-null outcome, Seam will process any appropriate JSF andSeam navigation rules, possibly resulting in a completely different page being rendered.

If all you want to do before rendering the page is begin a conversation, you could use a built-in actionmethod that does just that:

<pages> <page view-id="/messageList.jsp" action="#{messageManager.list}"/> ...</pages>

<pages> <page view-id="/messageList.jsp" action="#{conversation.begin}"/> ...

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

145

Page 151: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

NOTE

This built-in action can also be executed from a JSF control, and, similarly, you can use #{conversation.end} to end conversations.

If you want more control, to join existing conversations or begin a nested conversion, to begin apageflow or an atomic conversation, you should use the <begin-conversation> element.

There is also an <end-conversation> element.

To solve the first problem, we now have five options:

Annotate the @Create method with @Begin

Annotate the @Factory method with @Begin

Annotate the Seam page action method with @Begin

Use <begin-conversation> in pages.xml.

Use #{conversation.begin} as the Seam page action method

8.4. USING <S:LINK> AND <S:BUTTON>

JSF command links always perform a form submission via JavaScript, which breaks the web browser'sopen in new window or open in new tab feature. In plain JSF, you need to use an <h:outputLink> if youneed this functionality. But there are two major limitations to <h:outputLink>.

JSF provides no way to attach an action listener to an <h:outputLink>.

JSF does not propagate the selected row of a DataModel since there is no actual formsubmission.

Seam provides the notion of a page action to help solve the first problem, but this does nothing to helpus with the second problem. We could work around this by using the RESTful approach of passing arequest parameter and requerying for the selected object on the server side. In some cases—such asthe Seam blog example application—this is indeed the best approach. The RESTful style supports

</pages>

<pages> <page view-id="/messageList.jsp"> <begin-conversation nested="true" pageflow="AddItem"/> <page> ...</pages>

<pages> <page view-id="/home.jsp"> <end-conversation/> <page> ...</pages>

Seam 2 Reference Guide

146

Page 152: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

bookmarking, since it does not require server-side state. In other cases, where we don't care aboutbookmarks, the use of @DataModel and @DataModelSelection is just so convenient andtransparent!

To fill in this missing functionality, and to make conversation propagation even simpler to manage,Seam provides the <s:link> JSF tag.

The link may specify just the JSF view id:

Or, it may specify an action method (in which case the action outcome determines the page thatresults):

If you specify both a JSF view id and an action method, the view will be used unless the action methodreturns a non-null outcome:

The link automatically propagates the selected row of a DataModel using inside <h:dataTable>:

You can leave the scope of an existing conversation:

You can begin, end, or nest conversations:

If the link begins a conversation, you can even specify a pageflow to be used:

The taskInstance attribute is for use in jBPM task lists:

(See the DVD Store demo application for examples of this.)

Finally, if you need the "link" to be rendered as a button, use <s:button>:

8.5. SUCCESS MESSAGES

<s:link view="/login.xhtml" value="Login"/>

<s:link action="#{login.logout}" value="Logout"/>

<s:link view="/loggedOut.xhtml" action="#{login.logout}" value="Logout"/>

<s:link view="/hotel.xhtml" action="#{hotelSearch.selectHotel}" value="#{hotel.name}"/>

<s:link view="/main.xhtml" propagation="none"/>

<s:link action="#{issueEditor.viewComment}" propagation="nest"/>

<s:link action="#{documentEditor.getDocument}" propagation="begin" pageflow="EditDocument"/>

<s:link action="#{documentApproval.approveOrReject}" taskInstance="#{task}"/>

<s:button action="#{login.logout}" value="Logout"/>

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

147

Page 153: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

It is quite common to display a message to the user indicating success or failure of an action. It isconvenient to use a JSF FacesMessage for this. Unfortunately, a successful action often requires abrowser redirect, and JSF does not propagate faces messages across redirects. This makes it quitedifficult to display success messages in plain JSF.

The built in conversation-scoped Seam component named facesMessages solves this problem. (Youmust have the Seam redirect filter installed.)

Any message added to facesMessages is used in the very next render response phase for thecurrent conversation. This even works when there is no long-running conversation since Seampreserves even temporary conversation contexts across redirects.

You can even include JSF EL expressions in a faces message summary:

You may display the messages in the usual way, for example:

8.6. NATURAL CONVERSATION IDS

When working with conversations that deal with persistent objects, it may be desirable to use thenatural business key of the object instead of the standard, surrogate conversation id:

Easy redirect to existing conversation

It can be useful to redirect to an existing conversation if the user requests the same operation twice.Take this example:

You are on Ebay, half way through paying for an item you just won as a Christmas present for yourparents. Lets say you are sending it straight to them - you enter your payment details but you cannotremember their address. You accidentally reuse the same browser window finding out their address.Now you need to return to the payment for the item.

With a natural conversation its really easy to have the user rejoin the existing conversation, and pickup where they left off - just have them to rejoin the payForItem conversation with the itemId as theconversation ID.

User friendly URLs

This consists of a navigable hierarchy (I can navigate by editing the url) and a meaningful URL; for some

@Name("editDocumentAction")@Statelesspublic class EditDocumentBean implements EditDocument { @In EntityManager em; @In Document document; @In FacesMessages facesMessages; public String update() { em.merge(document); facesMessages.add("Document updated"); }}

facesMessages.add("Document #{document.title} was updated");

<h:messages globalOnly="true"/>

Seam 2 Reference Guide

148

Page 154: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

applications user friendly URLs are less important.

With a natural conversations, when you are building your hotel booking system (or, of course, whateveryour app is) you can generate a URL like http://seam-hotels/book.seam?hotel=BestWesternAntwerpen (of course, whatever parameter hotel maps to on your domainmodel must be unique) and with URLRewrite easily transform this to http://seam-hotels/book/BestWesternAntwerpen.

8.7. CREATING A NATURAL CONVERSATION

Natural conversations are defined in pages.xml:

The first thing to note from the above definition is that the conversation has a name, in this case PlaceBid. This name uniquely identifies this particular named conversation, and is used by the pagedefinition to identify a named conversation to participate in.

The next attribute, parameter-name defines the request parameter that will contain the naturalconversation ID, in place of the default conversation id parameter. In this example, the parameter-name is auctionId. This means that instead of a conversation parameter like cid=123 appearing inthe URL for your page, it will contain auctionId=765432 instead.

The last attribute in the above configuration, parameter-value, defines an EL expression used toevaluate the value of the natural business key to use as the conversation id. In this example, theconversation id will be the primary key value of the auction instance currently in scope.

Next, we define which pages will participate in the named conversation. This is done by specifying the conversation attribute for a page definition:

8.8. REDIRECTING TO A NATURAL CONVERSATION

When starting, or redirecting to, a natural conversation there are a number of options for specifying thenatural conversation name. Let us start by looking at the following page definition:

<conversation name="PlaceBid" parameter-name="auctionId" parameter-value="#{auction.auctionId}"/>

<page view-id="/bid.xhtml" conversation="PlaceBid" login-required="true"> <navigation from-action="#{bidAction.confirmBid}"> <rule if-outcome="success"> <redirect view-id="/auction.xhtml"> <param name="id" value="#{bidAction.bid.auction.auctionId}"/> </redirect> </rule> </navigation> </page>

<page view-id="/auction.xhtml"> <param name="id" value="#{auctionDetail.selectedAuctionId}"/> <navigation from-action="#{bidAction.placeBid}">

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

149

Page 155: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

From here, we can see that invoking the action #{bidAction.placeBid} from our auction view (bythe way, all these examples are taken from the seamBay example in Seam), that we will be redirectedto /bid.xhtml, which, as we saw previously, is configured with the natural conversation PlaceBid.The declaration for our action method looks like this:

When named conversations are specified in the <page/> element, redirection to the namedconversation occurs as part of navigation rules, after the action method has already been invoked. Thisis a problem when redirecting to an existing conversation, as redirection needs to be occur before theaction method is invoked. Therefore it is necessary to specify the conversation name when the actionis invoked. One way of doing this is by using the s:conversationName tag:

Another alternative is to specify the conversationName attribute when using either s:link or s:button:

8.9. WORKSPACE MANAGEMENT

Workspace management is the ability to switch conversations in a single window. Seam makesworkspace management completely transparent at the level of the Java code. To enable workspacemanagement, all you need to do is:

Provide description text for each view id (when using JSF or Seam navigation rules) or pagenode (when using jPDL pageflows). This description text is displayed to the user by theworkspace switchers.

Include one or more of the standard workspace switcher JSP or facelets fragments in yourpages. The standard fragments support workspace management via a drop down menu, a listof conversations, or breadcrumbs.

8.9.1. Workspace management and JSF navigation

When you use JSF or Seam navigation rules, Seam switches to a conversation by restoring the current view-id for that conversation. The descriptive text for the workspace is defined in a file called pages.xml that Seam expects to find in the WEB-INF directory, right next to faces-config.xml:

<redirect view-id="/bid.xhtml"/> </navigation> </page>

@Begin(join = true) public void placeBid()

<h:commandButton id="placeBidWithAmount" styleClass="placeBid" action="#{bidAction.placeBid}"> <s:conversationName value="PlaceBid"/> </h:commandButton>

<s:link value="Place Bid" action="#{bidAction.placeBid}" conversationName="PlaceBid"/>

<pages> <page view-id="/main.xhtml"> <description>Search hotels: #{hotelBooking.searchString}</description>

Seam 2 Reference Guide

150

Page 156: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

IMPORTANT

If this file is missing, the Seam application will continue to work perfectly, with the onlymissing functionality will be the ability to switch workspaces.

8.9.2. Workspace management and jPDL pageflow

When you use a jPDL pageflow definition, Seam switches to a conversation by restoring the currentjBPM process state. This is a more flexible model since it allows the same view-id to have differentdescriptions depending upon the current <page> node. The description text is defined by the <page>node:

8.9.3. The conversation switcher

Include the following fragment in your JSP or facelets page to get a drop-down menu that lets youswitch to any current conversation, or to any other page of the application:

</page> <page view-id="/hotel.xhtml"> <description>View hotel: #{hotel.name}</description> </page> <page view-id="/book.xhtml"> <description>Book hotel: #{hotel.name}</description> </page> <page view-id="/confirm.xhtml"> <description>Confirm: #{booking.description}</description> </page> </pages>

<pageflow-definition name="shopping">

<start-state name="start"> <transition to="browse"/> </start-state> <page name="browse" view-id="/browse.xhtml"> <description>DVD Search: #{search.searchPattern}</description> <transition to="browse"/> <transition name="checkout" to="checkout"/> </page> <page name="checkout" view-id="/checkout.xhtml"> <description>Purchase: $#{cart.total}</description> <transition to="checkout"/> <transition name="complete" to="complete"/> </page> <page name="complete" view-id="/complete.xhtml"> <end-conversation /> </page> </pageflow-definition>

<h:selectOneMenu value="#{switcher.conversationIdOrOutcome}">

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

151

Page 157: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

In this example, we have a menu that includes an item for each conversation, together with twoadditional items that let the user begin a new conversation.

Only conversations with a description (specified in pages.xml) will be included in the drop-downmenu.

8.9.4. The conversation list

The conversation list is very similar to the conversation switcher, except that it is displayed as a table:

<f:selectItem itemLabel="Find Issues" itemValue="findIssue"/> <f:selectItem itemLabel="Create Issue" itemValue="editIssue"/> <f:selectItems value="#{switcher.selectItems}"/></h:selectOneMenu><h:commandButton action="#{switcher.select}" value="Switch"/>

<h:dataTable value="#{conversationList}" var="entry" rendered="#{not empty conversationList}"> <h:column> <f:facet name="header">Workspace</f:facet> <h:commandLink action="#{entry.select}" value="#{entry.description}"/> <h:outputText value="[current]" rendered="#{entry.current}"/> </h:column> <h:column> <f:facet name="header">Activity</f:facet> <h:outputText value="#{entry.startDatetime}"> <f:convertDateTime type="time" pattern="hh:mm a"/> </h:outputText> <h:outputText value=" - "/> <h:outputText value="#{entry.lastDatetime}"> <f:convertDateTime type="time" pattern="hh:mm a"/> </h:outputText> </h:column> <h:column> <f:facet name="header">Action</f:facet> <h:commandButton action="#{entry.select}" value="#{msg.Switch}"/> <h:commandButton action="#{entry.destroy}" value="#{msg.Destroy}"/> </h:column></h:dataTable>

Seam 2 Reference Guide

152

Page 158: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We imagine that you will want to customize this for your own application.

Only conversations with a description will be included in the list.

Notice that the conversation list lets the user destroy workspaces.

8.9.5. Breadcrumbs

Breadcrumbs are useful in applications which use a nested conversation model. The breadcrumbs are alist of links to conversations in the current conversation stack:

8.10. CONVERSATIONAL COMPONENTS AND JSF COMPONENTBINDINGS

Conversational components have one minor limitation: they cannot be used to hold bindings to JSFcomponents. (We generally prefer not to use this feature of JSF unless absolutely necessary, since itcreates a hard dependency from application logic to the view.) On a postback request, componentbindings are updated during the Restore View phase, before the Seam conversation context has beenrestored.

To work around this use an event scoped component to store the component bindings and inject it intothe conversation scoped component that requires it.

<ui:repeat value="#{conversationStack}" var="entry"> <h:outputText value=" | "/> <h:commandLink value="#{entry.description}" action="#{entry.select}"/></ui:repeat

@Name("grid")@Scope(ScopeType.EVENT)public class Grid{ private HtmlPanelGrid htmlPanelGrid;

// getters and setters ...}

@Name("gridEditor")@Scope(ScopeType.CONVERSATION)public class GridEditor{ @In(required=false)

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

153

Page 159: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Also, you cannot inject a conversation scoped component into an event scoped component which youbind a JSF control to. This includes Seam built in components like facesMessages.

Alternatively, you can access the JSF component tree through the implicit uiComponent handle. Thefollowing example accesses getRowIndex()of the UIData component which backs the data tableduring iteration, it prints the current row number:

JSF UI components are available with their client identifier in this map.

8.11. CONCURRENT CALLS TO CONVERSATIONAL COMPONENTS

A general discussion of concurrent calls to Seam components can be found in Section 5.1.10,“Concurrency model”. Here we will discuss the most common situation in which you will encounterconcurrency — accessing conversational components from AJAX requests. We're going to discuss theoptions that a Ajax client library should provide to control events originating at the client — and we'lllook at the options RichFaces gives you.

Conversational components don't allow real concurrent access therefore Seam queues each request toprocess them serially. This allows each request to be executed in a deterministic fashion. However, asimple queue isn't that great. Firstly if a method is, for some reason, taking a very long time tocomplete, then running it over and over again whenever the client generates a request is a bad idea(potential for Denial of Service attacks). Secondly, AJAX is often used to provide a quick status updateto the user, so continuing to run the action after a long time isn't useful.

Therefore, when you are working inside a long running conversation, Seam queues the action event fora period of time (the concurrent request timeout); if it can't process the event in time, it creates atemporary conversation and prints out a message to the user to let them know what's going on. It istherefore very important not to flood the server with AJAX events.

We can set a sensible default for the concurrent request timeout (in ms) in components.xml:

We can also fine tune the concurrent request timeout on a page-by-page basis:

So far we have discussed serial AJAX requests - the client tells the server that an event has occur, andthen re-renders part of the page based on the result. This approach is great when the AJAX request islightweight (the methods called are simple for example, calculating the sum of a column of numbers).

private Grid grid; ...}

<h:dataTable id="lineItemTable" var="lineItem" value="#{orderHome.lineItems}"> <h:column> Row: #{uiComponent['lineItemTable'].rowIndex} </h:column> ...</h:dataTable>

<core:manager concurrent-request-timeout="500" />

<page view-id="/book.xhtml" conversation-required="true" login-required="true" concurrent-request-timeout="2000" />

Seam 2 Reference Guide

154

Page 160: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

But what if we need to do a complex computation?

For heavy computation we should use a truly asynchronous (poll based) approach — the client sends anAJAX request to the server, which causes action to be executed asynchronously on the server (so thethe response to the client is immediate); the client then polls the server for updates. This is useful whenyou have a long-running action for which it is important that every action executes (you do not wantsome to be dropped as duplicates, or to timeout).

8.11.1. How should we design our conversational AJAX application?

Well first, you need to decide whether you want to use the simpler synchronous request or whether youwant to add using a poll-style approach.

If you go for a synchronous approach, then you need to make an estimate of how long your AJAXrequest will take to complete - is it much shorter than the concurrent request timeout? If not, youprobably want to alter the concurrent request timeout for this method (as discussed above). Next youprobably want a queue on the client side to prevent flooding the server with requests. If the eventoccurs often (for example, a keypress, onblur of input fields) and immediate update of the client is not apriority you should set a request delay on the client side. When working out your request delay, factorin that the event may also be queued on the server side.

Finally, the client library may provide an option to abort unfinished duplicate requests in favor of themost recent. You need to be careful with this option as it can lead to flooding of the server withrequests if the server is not able to abort the unfinished request.

Using a poll-style design requires less fine-tuning. You just mark your action method @Asynchronousand decide on a polling interval:

8.11.2. Dealing with errors

However carefully you design your application to queue concurrent requests to your conversationalcomponent, there is a risk that the server will become overloaded and be unable to process all therequests before the request will have to wait longer than the concurrent-request-timeout. In thiscase Seam will throw a ConcurrentRequestTimeoutException which can be handled in pages.xml. We recommend sending a HTTP 503 error:

int total;

// This method is called when an event occurs on the client// It takes a really long time to execute@Asynchronous public void calculateTotal() { total = someReallyComplicatedCalculation();}

// This method is called as the result of the poll// It's very quick to executepublic int getTotal() { return total;}

<exception class="org.jboss.seam.ConcurrentRequestTimeoutException" logLevel="trace">

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

155

Page 161: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

NOTE

The server is currently unable to handle the request due to a temporary overloading ormaintenance of the server. The implication is that this is a temporary condition whichwill be alleviated after some delay.

Alternatively you could redirect to an error page:

ICEfaces, RichFaces Ajax and Seam Remoting can all handle HTTP error codes. Seam Remoting willpop up a dialog box showing the HTTP error and ICEfaces will indicate the error in it's connectionstatus component. RichFaces Ajax provides the most complete support for handling HTTP errors byproviding a user definable callback. For example, to show the error message to the user:

8.11.3. RichFaces Ajax

RichFaces Ajax is the AJAX library most commonly used with Seam, and provides all the controlsdiscussed above:

eventsQueue — provide a queue in which events are placed. All events are queued andrequests are sent to the server serially. This is useful if the request can to the server can takesome time to execute (e.g. heavy computation, retrieving information from a slow source) asthe server isn't flooded.

ignoreDupResponses — ignore the response produced by the request if a more recentsimilar request is already in the queue. ignoreDupResponses="true" does not cancel the theprocessing of the request on the server side — just prevents unnecessary updates on the clientside.

This option should be used with care with Seam's conversations as it allows multipleconcurrent requests to be made.

requestDelay — defines the time (in ms.) that the request will be remain on the queue. If therequest has not been processed by after this time the request will be sent (regardless ofwhether a response has been received) or discarded (if there is a more recent similar event onthe queue).

<http-error error-code="503" /></exception>

<exception class="org.jboss.seam.ConcurrentRequestTimeoutException" logLevel="trace"> <end-conversation/> <redirect view-id="/error.xhtml"> <message>The server is too busy to process your request, please try again later</message> </redirect></exception>

<script type="text/javascript"> A4J.AJAX.onError = function(req,status,message) { alert("message"); };</script>

Seam 2 Reference Guide

156

Page 162: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This option should be used with care with Seam's conversations as it allows multipleconcurrent requests to be made. You need to be sure that the delay you set (in combinationwith the concurrent request timeout) is longer than the action will take to execute.

<a:poll reRender="total" interval="1000" /> — Polls the server, and re-renders anarea as needed.

CHAPTER 8. CONVERSATIONS AND WORKSPACE MANAGEMENT

157

Page 163: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSESJBoss jBPM is a business process management engine for any Java SE or EE environment. jBPM letsyou represent a business process or user interaction as a graph of nodes representing wait states,decisions, tasks, web pages, etc. The graph is defined using a simple, very readable, XML dialect calledjPDL, and may be edited and visualised graphically using an eclipse plugin. jPDL is an extensiblelanguage, and is suitable for a range of problems, from defining web application page flow, totraditional workflow management, all the way up to orchestration of services in a SOA environment.

Seam applications use jBPM in two different situations:

Defining the pageflow involved in complex user interactions. A jPDL process definition definesthe page flow for a single conversation. A Seam conversation is considered to be a relativelyshort-running interaction with a single user.

Defining the overarching business process. The business process may span multipleconversations with multiple users. Its state is persistent in the jBPM database, so it isconsidered long-running. Coordination of the activities of multiple users is a much morecomplex problem than scripting an interaction with a single user, so jBPM offers sophisticatedfacilities for task management and dealing with multiple concurrent paths of execution.

Pageflow, conversation and task all refer to a single interaction with a single user and operate at verydifferent levels or granularity. A business process spans many tasks. Furthermore, the two applicationsof jBPM are totally orthogonal. You can use them together or independently or not at all.

You do not have to know jDPL to use Seam. If you are perfectly happy defining pageflow using JSF orSeam navigation rules, and if your application is more data-driven that process-driven, you probablydon't need jBPM. But we're finding that thinking of user interaction in terms of a well-defined graphicalrepresentation is helping us build more robust applications.

9.1. PAGEFLOW IN SEAM

There are two ways to define pageflow in Seam:

Using JSF or Seam navigation rules - the stateless navigation model

Using jPDL - the stateful navigation model

Very simple applications will only need the stateless navigation model while complex applications willuse both models in different places; each model has its strengths and weaknesses.

9.1.1. The two navigation models

The stateless model defines a mapping from a set of named, logical outcomes of an event directly tothe resulting page of the view. The navigation rules are entirely oblivious to any state held by theapplication other than what page was the source of the event. This means that your action listenermethods must sometimes make decisions about the page flow, since only they have access to thecurrent state of the application.

Here is an example page flow definition using JSF navigation rules:

<navigation-rule> <from-view-id>/numberGuess.jsp</from-view-id> <navigation-case>

Seam 2 Reference Guide

158

Page 164: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Here is the same example page flow definition using Seam navigation rules:

If you find navigation rules overly verbose, you can return view ids directly from your action listenermethods:

Note that this results in a redirect. You can even specify parameters to be used in the redirect:

<from-outcome>guess</from-outcome> <to-view-id>/numberGuess.jsp</to-view-id> <redirect/> </navigation-case>

<navigation-case> <from-outcome>win</from-outcome> <to-view-id>/win.jsp</to-view-id> <redirect/> </navigation-case> <navigation-case> <from-outcome>lose</from-outcome> <to-view-id>/lose.jsp</to-view-id> <redirect/> </navigation-case>

</navigation-rule>

<page view-id="/numberGuess.jsp"> <navigation> <rule if-outcome="guess"> <redirect view-id="/numberGuess.jsp"/> </rule> <rule if-outcome="win"> <redirect view-id="/win.jsp"/> </rule> <rule if-outcome="lose"> <redirect view-id="/lose.jsp"/> </rule> </navigation>

</page>

public String guess() { if (guess==randomNumber) return "/win.jsp"; if (++guessCount==maxGuesses) return "/lose.jsp"; return null;}

public String search() { return "/searchResults.jsp?searchPattern=#{searchAction.searchPattern}";}

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES

159

Page 165: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The stateful model defines a set of transitions between a set of named, logical application states. In thismodel, it is possible to express the flow of any user interaction entirely in the jPDL pageflow definition,and write action listener methods that are completely unaware of the flow of the interaction.

Here is an example page flow definition using jPDL:

<pageflow-definition name="numberGuess"> <start-page name="displayGuess" view-id="/numberGuess.jsp"> <redirect/> <transition name="guess" to="evaluateGuess"> <action expression="#{numberGuess.guess}" /> </transition> </start-page> <decision name="evaluateGuess" expression="#{numberGuess.correctGuess}"> <transition name="true" to="win"/> <transition name="false" to="evaluateRemainingGuesses"/> </decision> <decision name="evaluateRemainingGuesses" expression="#{numberGuess.lastGuess}"> <transition name="true" to="lose"/> <transition name="false" to="displayGuess"/> </decision> <page name="win" view-id="/win.jsp"> <redirect/> <end-conversation /> </page> <page name="lose" view-id="/lose.jsp"> <redirect/> <end-conversation /> </page> </pageflow-definition>

Seam 2 Reference Guide

160

Page 166: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

There are two things we notice immediately here:

The JSF/Seam navigation rules are much simpler. (However, this obscures the fact that theunderlying Java code is more complex.)

The jPDL makes the user interaction immediately understandable, without us needing to evenlook at the JSP or Java code.

In addition, the stateful model is more constrained. For each logical state (each step in the page flow),there are a constrained set of possible transitions to other states. The stateless model is an ad hocmodel which is suitable to relatively unconstrained, freeform navigation where the user decides wherehe/she wants to go next, not the application.

The stateful/stateless navigation distinction is quite similar to the traditional view of modal/modelessinteraction. Now, Seam applications are not usually modal in the simple sense of the word - indeed,avoiding application modal behavior is one of the main reasons for having conversations. However,Seam applications can be, and often are, modal at the level of a particular conversation. It is well-known that modal behavior is something to avoid as much as possible; it is very difficult to predict theorder in which your users are going to wish to opperate. However, there is no doubt that the statefulmodel has its place.

The biggest contrast between the two models is the back-button behavior.

9.1.2. Seam and the back button

When JSF or Seam navigation rules are used, Seam lets the user freely navigate via the back, forwardand refresh buttons. It is the responsibility of the application to ensure that conversational stateremains internally consistent when this occurs. Experience with the combination of web applicationframeworks like Struts or WebWork - that do not support a conversational model - and statelesscomponent models like EJB stateless session beans or the Spring framework has taught manydevelopers that this is close to impossible to do! However, our experience is that in the context ofSeam, where there is a well-defined conversational model, backed by stateful session beans, it isactually quite straightforward. Usually it is as simple as combining the use of no-conversation-view-id with null checks at the beginning of action listener methods. We consider support forfreeform navigation to be almost always desirable.

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES

161

Page 167: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

In this case, the no-conversation-view-id declaration goes in pages.xml. It tells Seam toredirect to a different page if a request originates from a page rendered during a conversation, andthat conversation no longer exists:

On the other hand, in the stateful model, backbuttoning is interpreted as an undefined transition backto a previous state. Since the stateful model enforces a defined set of transitions from the currentstate, back buttoning is by default disallowed in the stateful model. Seam transparently detects theuse of the back button, and blocks any attempt to perform an action from a previous, stale page, andsimply redirects the user to the current page (and displays a faces message). Whether you consider thisa feature or a limitation of the stateful model depends upon your point of view: as an applicationdeveloper, it is a feature; as a user, it might be frustrating. You can enable backbutton navigation from aparticular page node by setting back="enabled".

This allows backbuttoning from the checkout state to any previous state!

Of course, we still need to define what happens if a request originates from a page rendered during apageflow, and the conversation with the pageflow no longer exists. In this case, the no-conversation-view-id declaration goes into the pageflow definition:

In practice, both navigation models have their place, and you'll quickly learn to recognize when toprefer one model over the other.

9.2. USING JPDL PAGEFLOWS

9.2.1. Installing pageflows

We need to install the Seam jBPM-related components, and tell them where to find our pageflowdefinition. We can specify this Seam configuration in components.xml.

<page view-id="/checkout.xhtml" no-conversation-view-id="/main.xhtml"/>

<page name="checkout" view-id="/checkout.xhtml" back="enabled"> <redirect/> <transition to="checkout"/> <transition name="complete" to="complete"/></page>

<page name="checkout" view-id="/checkout.xhtml" back="enabled" no-conversation-view-id="/main.xhtml"> <redirect/> <transition to="checkout"/> <transition name="complete" to="complete"/></page>

<bpm:jbpm> <bpm:pageflow-definitions> <value>pageflow.jpdl.xml</value>

Seam 2 Reference Guide

162

Page 168: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The first line installs jBPM, the second points to a jPDL-based pageflow definition.

9.2.2. Starting pageflows

We start a jPDL-based pageflow by specifying the name of the process definition using a @Begin, @BeginTask or @StartTask annotation:

Alternatively we can start a pageflow using pages.xml:

If we are beginning the pageflow during the RENDER_RESPONSE phase—during a @Factory or @Create method, for example—we consider ourselves to be already at the page being rendered, anduse a <start-page> node as the first node in the pageflow, as in the example above.

But if the pageflow is begun as the result of an action listener invocation, the outcome of the actionlistener determines which is the first page to be rendered. In this case, we use a <start-state> asthe first node in the pageflow, and declare a transition for each possible outcome:

9.2.3. Page nodes and transitions

Each <page> node represents a state where the system is waiting for user input:

</bpm:pageflow-definitions></bpm:jbpm>

@Begin(pageflow="numberguess")public void begin() { ... }

<page> <begin-conversation pageflow="numberguess"/> </page>

<pageflow-definition name="viewEditDocument">

<start-state name="start"> <transition name="documentFound" to="displayDocument"/> <transition name="documentNotFound" to="notFound"/> </start-state> <page name="displayDocument" view-id="/document.jsp"> <transition name="edit" to="editDocument"/> <transition name="done" to="main"/> </page> ... <page name="notFound" view-id="/404.jsp"> <end-conversation/> </page> </pageflow-definition>

<page name="displayGuess" view-id="/numberGuess.jsp"> <redirect/>

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES

163

Page 169: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The view-id is the JSF view id. The <redirect/> element has the same effect as <redirect/> in aJSF navigation rule: namely, a post-then-redirect behavior, to overcome problems with the browser'srefresh button (note that Seam propagates conversation contexts over these browser redirects).

The transition name is the name of a JSF outcome triggered by clicking a command button orcommand link in numberGuess.jsp.

When the transition is triggered by clicking this button, jBPM will activate the transition action bycalling the guess() method of the numberGuess component. Notice that the syntax used forspecifying actions in the jPDL is just a familiar JSF EL expression, and that the transition actionhandler is just a method of a Seam component in the current Seam contexts. So we have exactly thesame event model for jBPM events that we already have for JSF events! (The One Kind of Stuffprinciple.)

In the case of a null outcome (for example, a command button with no action defined), Seam willsignal the transition with no name if one exists, or else simply redisplay the page if all transitions havenames. So we could slightly simplify our example pageflow and this button:

Would fire the following un-named transition:

It is even possible to have the button call an action method, in which case the action outcome willdetermine the transition to be taken:

However, this is considered an inferior style, since it moves responsibility for controlling the flow out ofthe pageflow definition and back into the other components. It is much better to centralize thisconcern in the pageflow itself.

9.2.4. Controlling the flow

<transition name="guess" to="evaluateGuess"> <action expression="#{numberGuess.guess}" /> </transition></page>

<h:commandButton type="submit" value="Guess" action="guess"/>

<h:commandButton type="submit" value="Guess"/>

<page name="displayGuess" view-id="/numberGuess.jsp"> <redirect/> <transition to="evaluateGuess"> <action expression="#{numberGuess.guess}" /> </transition></page>

<h:commandButton type="submit" value="Guess" action="#{numberGuess.guess}"/>

<page name="displayGuess" view-id="/numberGuess.jsp"> <transition name="correctGuess" to="win"/> <transition name="incorrectGuess" to="evaluateGuess"/></page>

Seam 2 Reference Guide

164

Page 170: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Usually, we don't need the more powerful features of jPDL when defining pageflows. We do need the <decision> node, however:

A decision is made by evaluating a JSF EL expression in the Seam contexts.

9.2.5. Ending the flow

We end the conversation using <end-conversation> or @End. (In fact, for readability, use of both isencouraged.)

Optionally, we can end a task, specify a jBPM transition name. In this case, Seam will signal the endof the current task in the overarching business process.

9.2.6. Pageflow composition

It is possible to compose pageflows and have one pageflow pause pause while another pageflowexecutes. The <process-state> node pauses the outer pageflow, and begins execution of a namedpageflow:

The inner flow begins executing at a <start-state> node. When it reaches an <end-state> node,execution of the inner flow ends, and execution of the outer flow resumes with the transition definedby the <process-state> element.

9.3. BUSINESS PROCESS MANAGEMENT IN SEAM

A business process is a well-defined set of tasks that must be performed by users or software systemsaccording to well-defined rules about who can perform a task, and when it should be performed. Seam'sjBPM integration makes it easy to display lists of tasks to users and let them manage their tasks. Seamalso lets the application store state associated with the business process in the BUSINESS_PROCESScontext, and have that state made persistent via jBPM variables.

A simple business process definition looks much the same as a page flow definition (One Kind of Stuff),except that instead of <page> nodes, we have <task-node> nodes. In a long-running business

<decision name="evaluateGuess" expression="#{numberGuess.correctGuess}"> <transition name="true" to="win"/> <transition name="false" to="evaluateRemainingGuesses"/></decision>

<page name="win" view-id="/win.jsp"> <redirect/> <end-conversation/></page>

<page name="win" view-id="/win.jsp"> <redirect/> <end-task transition="success"/></page>

<process-state name="cheat"> <sub-process name="cheat"/> <transition to="displayGuess"/></process-state>

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES

165

Page 171: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

process, the wait states are where the system is waiting for some user to log in and perform a task.

It is perfectly possible that we might have both jPDL business process definitions and jPDL pageflowdefinitions in the same project. If so, the relationship between the two is that a single <task> in abusiness process corresponds to a whole pageflow <pageflow-definition>

9.4. USING JPDL BUSINESS PROCESS DEFINITIONS

9.4.1. Installing process definitions

We need to install jBPM, and tell it where to find the business process definitions:

As jBPM processes are persistent across application restarts, when using Seam in a production

<process-definition name="todo"> <start-state name="start"> <transition to="todo"/> </start-state> <task-node name="todo"> <task name="todo" description="#{todoList.description}"> <assignment actor-id="#{actor.id}"/> </task> <transition to="done"/> </task-node> <end-state name="done"/> </process-definition>

<bpm:jbpm> <bpm:process-definitions> <value>todo.jpdl.xml</value> </bpm:process-definitions></bpm:jbpm>

Seam 2 Reference Guide

166

Page 172: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

environment you won't want to install the process definition every time the application starts.Therefore, in a production environment, you will need to deploy the process to jBPM outside of Seam.In other words, only install process definitions from components.xml when developing yourapplication.

9.4.2. Initializing actor ids

We always need to know what user is currently logged in. jBPM recognizes users by their actor id andgroup actor ids. We specify the current actor ids using the built in Seam component named actor:

9.4.3. Initiating a business process

To initiate a business process instance, we use the @CreateProcess annotation:

Alternatively we can initiate a business process using pages.xml:

9.4.4. Task assignment

When a process reaches a task node, task instances are created. These must be assigned to users oruser groups. We can either hardcode our actor IDs, or delegate to a Seam component:

In this case, we have simply assigned the task to the current user. We can also assign tasks to a pool:

9.4.5. Task lists

Several built-in Seam components make it easy to display task lists. The pooledTaskInstanceListis a list of pooled tasks that users may assign to themselves:

@In Actor actor;

public String login() { ... actor.setId( user.getUserName() ); actor.getGroupActorIds().addAll( user.getGroupNames() ); ...}

@CreateProcess(definition="todo")public void createTodo() { ... }

<page> <create-process definition="todo" /></page>

<task name="todo" description="#{todoList.description}"> <assignment actor-id="#{actor.id}"/></task>

<task name="todo" description="#{todoList.description}"> <assignment pooled-actors="employees"/></task>

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES

167

Page 173: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Note that instead of <s:link> we could have used a plain JSF <h:commandLink>:

The pooledTask component is a built-in component that simply assigns the task to the current user.

The taskInstanceListForType component includes tasks of a particular type that are assigned tothe current user:

9.4.6. Performing a task

To begin work on a task, we use either @StartTask or @BeginTask on the listener method:

Alternatively we can begin work on a task using pages.xml:

These annotations begin a special kind of conversation that has significance in terms of theoverarching business process. Work done by this conversation has access to state held in the businessprocess context.

If we end the conversation using @EndTask, Seam will signal the completion of the task:

<h:dataTable value="#{pooledTaskInstanceList}" var="task"> <h:column> <f:facet name="header">Description</f:facet> <h:outputText value="#{task.description}"/> </h:column> <h:column> <s:link action="#{pooledTask.assignToCurrentActor}" value="Assign" taskInstance="#{task}"/> </h:column> </h:dataTable>

<h:commandLink action="#{pooledTask.assignToCurrentActor}"> <f:param name="taskId" value="#{task.id}"/></h:commandLink>

<h:dataTable value="#{taskInstanceListForType['todo']}" var="task"> <h:column> <f:facet name="header">Description</f:facet> <h:outputText value="#{task.description}"/> </h:column> <h:column> <s:link action="#{todoList.start}" value="Start Work" taskInstance="#{task}"/> </h:column> </h:dataTable>

@StartTaskpublic String start() { ... }

<page> <start-task /></page>

Seam 2 Reference Guide

168

Page 174: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Alternatively we can use pages.xml:

You can also use EL to specify the transition in pages.xml.

At this point, jBPM takes over and continues executing the business process definition. (In morecomplex processes, several tasks might need to be completed before process execution can resume.)

Please refer to the jBPM documentation for a more thorough overview of the sophisticated featuresthat jBPM provides for managing complex business processes.

@EndTask(transition="completed")public String completed() { ... }

<page> <end-task transition="completed" /></page>

CHAPTER 9. PAGEFLOWS AND BUSINESS PROCESSES

169

Page 175: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 10. SEAM AND OBJECT/RELATIONAL MAPPINGSeam provides extensive support for the two most popular persistence architectures for Java:Hibernate3, and the Java Persistence API introduced with EJB 3.0. Seam's unique state-managementarchitecture allows the most sophisticated ORM integration of any web application framework.

10.1. INTRODUCTION

Seam grew out of the frustration of the Hibernate team with the statelessness typical of the previousgeneration of Java application architectures. The state management architecture of Seam wasoriginally designed to solve problems relating to persistence—in particular problems associated withoptimistic transaction processing. Scalable online applications always use optimistic transactions. Anatomic (database/JTA) level transaction should not span a user interaction unless the application isdesigned to support only a very small number of concurrent clients. But almost all interesting workinvolves first displaying data to a user, and then, slightly later, updating the same data. So Hibernatewas designed to support the idea of a persistence context which spanned an optimistic transaction.

Unfortunately, the stateless architectures that preceded Seam and EJB 3.0 had no construct forrepresenting an optimistic transaction. So, instead, these architectures provided persistence contextsscoped to the atomic transaction. This resulted in many problems for users. What we need is aconstruct for representing an optimistic transaction in the application tier.

EJB 3.0 recognizes this problem, and introduces the idea of a stateful component (a stateful sessionbean) with an extended persistence context scoped to the lifetime of the component. This is a partialsolution to the problem (and is a useful construct in and of itself) however there are two problems:

The lifecycle of the stateful session bean must be managed manually via code in the web tier(it turns out that this is a subtle problem and much more difficult in practice than it sounds).

Propagation of the persistence context between stateful components in the same optimistictransaction is possible, but tricky.

Seam solves the first problem by providing conversations, and stateful session bean componentsscoped to the conversation. (Most conversations actually represent optimistic transactions in the datalayer.) This is sufficient for many simple applications (such as the Seam booking demo) wherepersistence context propagation is not needed. For more complex applications, with many loosly-interacting components in each conversation, propagation of the persistence context acrosscomponents becomes an important issue. So Seam extends the persistence context managementmodel of EJB 3.0, to provide conversation-scoped extended persistence contexts.

10.2. SEAM MANAGED TRANSACTIONS

EJB session beans feature declarative transaction management. The EJB container is able to start atransaction transparently when the bean is invoked, and end it when the invocation ends. If we write asession bean method that acts as a JSF action listener, we can do all the work associated with thataction in one transaction, and be sure that it is committed or rolled back when we finish processing theaction. This is a great feature, and all that is needed by some Seam applications.

However, there is a problem with this approach. A Seam application may not perform all data accessfor a request from a single method call to a session bean.

The request might require processing by several loosly-coupled components, each of which iscalled independently from the web layer. It is common to see several or even many calls perrequest from the web layer to EJB components in Seam.

Seam 2 Reference Guide

170

Page 176: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Rendering of the view might require lazy fetching of associations.

The more transactions per request, the more likely we are to encounter atomicity and isolationproblems when our application is processing many concurrent requests. Certainly, all write operationsshould occur in the same transaction.

Hibernate users developed the open session in view pattern to work around this problem. In theHibernate community, "open session in view" was historically even more important becauseframeworks like Spring use transaction-scoped persistence contexts. So rendering the view wouldcause LazyInitializationExceptions when unfetched associations were accessed.

This pattern is usually implemented as a single transaction which spans the entire request. There areseveral problems with this implementation, the most serious being that we can never be sure that atransaction is successful until we commit it—but by the time the open session in view transaction iscommitted, the view is fully rendered, and the rendered response may already have been flushed to theclient. How can we notify the user that their transaction was unsuccessful?

Seam solves both the transaction isolation problem and the association fetching problem, whileworking around the problems with open session in view. The solution comes in two parts:

Use an extended persistence context that is scoped to the conversation, instead of to thetransaction

Use two transactions per request; the first spans the beginning of the restore view phase(some transaction managers begin the transaction later at the beginning of the apply requestvaues phase) until the end of the invoke application phase; the second spans the renderresponse phase

In the next section, we will tell you how to set up a conversation-scope persistence context. But firstwe need to tell you how to enable Seam transaction management. Note that you can use conversation-scoped persistence contexts without Seam transaction management, and there are good reasons touse Seam transaction management even when you are not using Seam-managed persistence contexts.However, the two facilities were designed to work together, and work best when used together.

Seam transaction management is useful even if you are using EJB 3.0 container-managed persistencecontexts. But it is especially useful if you use Seam outside a Java EE 5 environment, or in any othercase where you would use a Seam-managed persistence context.

10.2.1. Disabling Seam-managed transactions

Seam transaction management is enabled by default for all JSF requests. If you want to disable thisfeature, you can do it in components.xml:

10.2.2. Configuring a Seam transaction manager

Seam provides a transaction management abstraction for beginning, committing, rolling back, andsynchronizing with a transaction. By default Seam uses a JTA transaction component that integrateswith Container Managed and programmatic EJB transactions. If you are working in a Java EE 5environment, you should install the EJB synchronization component in components.xml:

<core:init transaction-management-enabled="false"/> <transaction:no-transaction />

<transaction:ejb-transaction />

CHAPTER 10. SEAM AND OBJECT/RELATIONAL MAPPING

171

Page 177: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

However, if you are working in a non EE 5 container, Seam will try auto detect the transactionsynchronization mechanism to use. However, if Seam is unable to detect the correct transactionsynchronization to use, you may find you need configure one of the following:

JPA RESOURCE_LOCAL transactions with the javax.persistence.EntityTransactioninterface. EntityTransaction begins the transaction at the beginning of the apply requestvalues phase.

Hibernate managed transactions with the org.hibernate.Transaction interface. HibernateTransaction begins the transaction at the beginning of the apply request valuesphase.

Spring managed transactions with the org.springframework.transaction.PlatformTransactionManager interface. TheSpring PlatformTransactionManagement manager may begin the transaction at thebeginning of the apply request values phase if the userConversationContext attribute isset.

Explicitly disable Seam managed transactions

Configure JPA RESOURCE_LOCAL transaction management by adding the following to yourcomponents.xml where #{em} is the name of the persistence:managed-persistence-contextcomponent. If your managed persistence context is named entityManager, you can opt to leave outthe entity-manager attribute. (see Section 10.3, “Seam-managed persistence contexts”Seam-managed persistence contexts)

To configure Hibernate managed transactions declare the following in your components.xml where #{hibernateSession} is the name of the project's persistence:managed-hibernate-sessioncomponent. If your managed hibernate session is named session, you can opt to leave out the session attribute. (see Section 10.3, “Seam-managed persistence contexts”Seam-managedpersistence contexts)

To explicitly disable Seam managed transactions declare the following in your components.xml:

For configuring Spring managed transactions see Section 24.5, “Using SpringPlatformTransactionManagement”using Spring PlatformTransactionManagement. .

10.2.3. Transaction synchronization

Transaction synchronization provides callbacks for transaction related events such as beforeCompletion() and afterCompletion(). By default, Seam uses its own transactionsynchronization component which requires explicit use of the Seam transaction component whencommitting a transaction to ensure synchronization callbacks are correctly executed. If in a Java EE 5environment the <transaction:ejb-transaction/> component should be be declared in components.xml to ensure that Seam synchronization callbacks are correctly called if the containercommits a transaction outside of Seam's knowledge.

<transaction:entity-transaction entity-manager="#{em}"/>

<transaction:hibernate-transaction session="#{hibernateSession}"/>

<transaction:no-transaction />

Seam 2 Reference Guide

172

Page 178: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

10.3. SEAM-MANAGED PERSISTENCE CONTEXTS

If you are using Seam outside of a Java EE 5 environment, you can't rely upon the container to managethe persistence context lifecycle for you. Even if you are in an EE 5 environment, you might have acomplex application with many loosly coupled components that collaborate together in the scope of asingle conversation, and in this case you might find that propagation of the persistence contextbetween component is tricky and error-prone.

In either case, you will need to use a managed persistence context (for JPA) or a managed session (forHibernate) in your components. A Seam-managed persistence context is just a built-in Seamcomponent that manages an instance of EntityManager or Session in the conversation context.You can inject it with @In.

Seam-managed persistence contexts are extremely efficient in a clustered environment. Seam is ableto perform an optimization that EJB 3.0 specification does not allow containers to use for container-managed extended persistence contexts. Seam supports transparent failover of extended persistencecontexts, without the need to replicate any persistence context state between nodes. (We hope to fixthis oversight in the next revision of the EJB spec.)

10.3.1. Using a Seam-managed persistence context with JPA

Configuring a managed persistence context is easy. In components.xml, we can write:

This configuration creates a conversation-scoped Seam component named bookingDatabase thatmanages the lifecycle of EntityManager instances for the persistence unit(EntityManagerFactory instance) with JNDI name java:/EntityManagerFactories/bookingData.

Of course, you need to make sure that you have bound the EntityManagerFactory into JNDI. InJBoss, you can do this by adding the following property setting to persistence.xml.

Now we can have our EntityManager injected using:

If you are using EJB3 and mark your class or method @TransactionAttribute(REQUIRES_NEW)then the transaction and persistence context shouldn't be propagated to method calls on this object.However as the Seam-managed persistence context is propagated to any component within theconversation, it will be propagated to methods marked REQUIRES_NEW. Therefore, if you mark amethod REQUIRES_NEW then you should access the entity manager using @PersistenceContext.

10.3.2. Using a Seam-managed Hibernate session

Seam-managed Hibernate sessions are similar. In components.xml:

<persistence:managed-persistence-context name="bookingDatabase" auto-create="true" persistence-unit-jndi-name="java:/EntityManagerFactories/bookingData"/>

<property name="jboss.entity.manager.factory.jndi.name" value="java:/EntityManagerFactories/bookingData"/>

@In EntityManager bookingDatabase;

CHAPTER 10. SEAM AND OBJECT/RELATIONAL MAPPING

173

Page 179: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Where java:/bookingSessionFactory is the name of the session factory specified in hibernate.cfg.xml.

IMPORTANT

Seam does not flush the session, so you should always enable hibernate.transaction.flush_before_completion to ensure that the sessionis automatically flushed before the JTA transaction commits.

We can now have a managed Hibernate Session injected into our JavaBean components using thefollowing code:

10.3.3. Seam-managed persistence contexts and atomic conversations

Persistence contexts scoped to the conversation allows you to program optimistic transactions thatspan multiple requests to the server without the need to use the merge() operation , without the needto re-load data at the beginning of each request, and without the need to wrestle with the LazyInitializationException or NonUniqueObjectException.

As with any optimistic transaction management, transaction isolation and consistency can be achievedvia use of optimistic locking. Fortunately, both Hibernate and EJB 3.0 make it very easy to useoptimistic locking, by providing the @Version annotation.

By default, the persistence context is flushed (synchronized with the database) at the end of eachtransaction. This is sometimes the desired behavior. But very often, we would prefer that all changesare held in memory and only written to the database when the conversation ends successfully. Thisallows for truly atomic conversations. As the result of a truly stupid and shortsighted decision bycertain non-JBoss, non-Sun and non-Sybase members of the EJB 3.0 expert group, there is currently

<persistence:hibernate-session-factory name="hibernateSessionFactory"/>

<persistence:managed-hibernate-session name="bookingDatabase" auto-create="true" session-factory-jndi-name="java:/bookingSessionFactory"/>

<session-factory name="java:/bookingSessionFactory"> <property name="transaction.flush_before_completion">true</property> <property name="connection.release_mode">after_statement</property> <property name="transaction.manager_lookup_class">org.hibernate.transaction.JBossTransactionManagerLookup</property> <property name="transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property> <property name="connection.datasource">java:/bookingDatasource</property> ...</session-factory>

@In Session bookingDatabase;

Seam 2 Reference Guide

174

Page 180: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

no simple, usable and portable way to implement atomic conversations using EJB 3.0 persistence.However, Hibernate provides this feature as a vendor extension to the FlushModeTypes defined bythe specification, and it is our expectation that other vendors will soon provide a similar extension.

Seam lets you specify FlushModeType.MANUAL when beginning a conversation. Currently, this worksonly when Hibernate is the underlying persistence provider, but we plan to support other equivalentvendor extensions.

Now, the claim object remains managed by the persistence context for the rest to the conversation.We can make changes to the claim:

But these changes will not be flushed to the database until we explicitly force the flush to occur:

Of course, you could set the flushMode to MANUAL from pages.xml, for example in a navigation rule:

10.4. USING THE JPA DELEGATE

The EntityManager interface lets you access a vendor-specific API via the getDelegate() method.Naturally, the most interesting vendor is Hibernate, and the most powerful delegate interface is org.hibernate.Session. You'd be nuts to use anything else. Trust me, I'm not biased at all. If youmust use a different JPA provider see Section 26.2, “Using Alternate JPA Providers” Using AlternateJPA Providers.

But regardless of whether you are using Hibernate or something else you will almost certainly want touse the delegate in your Seam components from time to time. One approach would be the following:

@In EntityManager em; //a Seam-managed persistence context

@Begin(flushMode=MANUAL)public void beginClaimWizard() { claim = em.find(Claim.class, claimId);}

public void addPartyToClaim() { Party party = ....; claim.addParty(party);}

@Endpublic void commitClaim() { em.flush();}

<begin-conversation flush-mode="MANUAL" />

@In EntityManager entityManager;

@Createpublic void init() { ( (Session) entityManager.getDelegate() ).enableFilter("currentVersions");}

CHAPTER 10. SEAM AND OBJECT/RELATIONAL MAPPING

175

Page 181: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Since most users avoid typecasts within the Java language, an alternative method to acessing thedelegate is described. First, add the following line to components.xml:

Now we can inject the session directly:

10.5. USING EL IN EJB-QL/HQL

Seam proxies the EntityManager or Session object whenever you use a Seam-managedpersistence context or inject a container managed persistence context using @PersistenceContext.This lets you use EL expressions in your query strings, safely and efficiently. For example, this:

is equivalent to:

The other way in which this can be written is not advised but included for completeness:

(It is inefficient and vulnerable to SQL injection attacks.)

10.6. USING HIBERNATE FILTERS

The most unique feature of Hibernate is filters. Filters let you provide a restricted view of the data inthe database. You can find out more about filters in the Hibernate documentation. Mentioned here is aneasy way to incorporate filters into a Seam application, one that works especially well with the SeamApplication Framework.

Seam-managed persistence contexts may have a list of filters defined, which will be enabled wheneveran EntityManager or Hibernate Session is first created. (They can also be used when anotherunderlying persistence provider is in use.)

<factory name="session" scope="STATELESS" auto-create="true" value="#{entityManager.delegate}"/>

@In Session session;

@Createpublic void init() { session.enableFilter("currentVersions");}

User user = em.createQuery("from User where username=#{user.username}") .getSingleResult();

User user = em.createQuery("from User where username=:username") .setParameter("username", user.getUsername()) .getSingleResult();

User user = em.createQuery("from User where username=" + user.getUsername()) .getSingleResult();

<persistence:filter name="regionFilter">

Seam 2 Reference Guide

176

Page 182: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<persistence:name>region</persistence:name> <persistence:parameters> <key>regionCode</key> <value>#{region.code}</value> </persistence:parameters></persistence:filter>

<persistence:filter name="currentFilter"> <persistence:name>current</persistence:name> <persistence:parameters> <key>date</key> <value>#{currentDate}</value> </persistence:parameters></persistence:filter>

<persistence:managed-persistence-context name="personDatabase" persistence-unit-jndi-name="java:/EntityManagerFactories/personDatabase"> <core:filters> <value>#{regionFilter}</value> <value>#{currentFilter}</value> </core:filters></persistence:managed-persistence-context>

CHAPTER 10. SEAM AND OBJECT/RELATIONAL MAPPING

177

Page 183: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 11. JSF FORM VALIDATION IN SEAMIn plain JSF, validation is defined in the view:

In practice, this approach usually violates DRY, since most validation actually enforces constraints thatare part of the data model, and exist all the way down to the database schema definition. Seamprovides support for model-based constraints defined using Hibernate Validator.

Let us start by defining our constraints, on our Location class:

Though default constraints are used here, in practice it might be more elegant to use customconstraints instead of the ones built into Hibernate Validator:

<h:form> <h:messages/>

<div> Country: <h:inputText value="#{location.country}" required="true"> <my:validateCountry/> </h:inputText> </div> <div> Zip code: <h:inputText value="#{location.zip}" required="true"> <my:validateZip/> </h:inputText> </div>

<h:commandButton/></h:form>

public class Location { private String country; private String zip; @NotNull @Length(max=30) public String getCountry() { return country; } public void setCountry(String c) { country = c; }

@NotNull @Length(max=6) @Pattern("^\d*$") public String getZip() { return zip; } public void setZip(String z) { zip = z; }}

public class Location { private String country; private String zip; @NotNull @Country

Seam 2 Reference Guide

178

Page 184: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Whichever route we take, we no longer need to specify the type of validation to be used in the JSFpage. Instead, we can use <s:validate> to validate against the constraint defined on the modelobject.

NOTE

Specifying @NotNull on the model does not eliminate the requirement for required="true" to appear on the control. This is due to a limitation of the JSFvalidation architecture.

This approach defines constraints on the model, and presents constraint violations in the view—asignificantly better design.

However, it is not much less verbose than what we started with, so let's try <s:validateAll>:

public String getCountry() { return country; } public void setCountry(String c) { country = c; }

@NotNull @ZipCode public String getZip() { return zip; } public void setZip(String z) { zip = z; }}

<h:form> <h:messages/>

<div> Country: <h:inputText value="#{location.country}" required="true"> <s:validate/> </h:inputText> </div> <div> Zip code: <h:inputText value="#{location.zip}" required="true"> <s:validate/> </h:inputText> </div> <h:commandButton/>

</h:form>

<h:form> <h:messages/>

<s:validateAll>

<div> Country: <h:inputText value="#{location.country}" required="true"/>

CHAPTER 11. JSF FORM VALIDATION IN SEAM

179

Page 185: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This tag simply adds an <s:validate> to every input in the form. For a large form, it can save a lot oftyping.

Now we need to do something about displaying feedback to the user when validation fails. Currently weare displaying all messages at the top of the form. What we would really like to do is display themessage next to the field with the error (this is possible in plain JSF), highlight the field and label (thisis not possible) and, for good measure, display some image next to the field (also not possible). We alsowant to display a little colored asterisk next to the label for each required form field.

That is quite a lot of functionality we need for each field of our form. We would not want to have tospecify highlighting and the layout of the image, message and input field for every field on the form. So,instead, we will specify the common layout in a facelets template:

We can include this template for each of our form fields using <s:decorate>.

</div>

<div> Zip code: <h:inputText value="#{location.zip}" required="true"/> </div>

<h:commandButton/>

</s:validateAll>

</h:form>

<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:s="http://jboss.com/products/seam/taglib"> <div> <s:label styleClass="#{invalid?'error':''}"> <ui:insert name="label"/> <s:span styleClass="required" rendered="#{required}">*</s:span> </s:label> <span class="#{invalid?'error':''}"> <h:graphicImage value="/img/error.gif" rendered="#{invalid}"/> <s:validateAll> <ui:insert/> </s:validateAll> </span> <s:message styleClass="error"/> </div> </ui:composition>

<h:form>

Seam 2 Reference Guide

180

Page 186: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Finally, we can use RichFaces Ajax to display validation messages as the user is navigating around theform:

It is better style to define explicit IDs for important controls on the page, especially if you want to doautomated testing for the UI, using some toolkit like Selenium. If you don't provide explicit ids, JSF willgenerate them, but the generated values will change if you change anything on the page.

<h:messages globalOnly="true"/>

<s:decorate template="edit.xhtml"> <ui:define name="label">Country:</ui:define> <h:inputText value="#{location.country}" required="true"/> </s:decorate> <s:decorate template="edit.xhtml"> <ui:define name="label">Zip code:</ui:define> <h:inputText value="#{location.zip}" required="true"/> </s:decorate>

<h:commandButton/>

</h:form>

<h:form>

<h:messages globalOnly="true"/>

<s:decorate id="countryDecoration" template="edit.xhtml"> <ui:define name="label">Country:</ui:define> <h:inputText value="#{location.country}" required="true"> <a:support event="onblur" reRender="countryDecoration" bypassUpdates="true"/> </h:inputText> </s:decorate> <s:decorate id="zipDecoration" template="edit.xhtml"> <ui:define name="label">Zip code:</ui:define> <h:inputText value="#{location.zip}" required="true"> <a:support event="onblur" reRender="zipDecoration" bypassUpdates="true"/> </h:inputText> </s:decorate>

<h:commandButton/>

</h:form>

<h:form id="form">

<h:messages globalOnly="true"/>

<s:decorate id="countryDecoration" template="edit.xhtml"> <ui:define name="label">Country:</ui:define> <h:inputText id="country" value="#{location.country}"

CHAPTER 11. JSF FORM VALIDATION IN SEAM

181

Page 187: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If you wish to specify a different message to be displayed when validation fails you can use the Seammessage bundle (and options like el expressions inside the message, and per-view message bundles)with the Hibernate Validator:

required="true"> <a:support event="onblur" reRender="countryDecoration" bypassUpdates="true"/> </h:inputText> </s:decorate> <s:decorate id="zipDecoration" template="edit.xhtml"> <ui:define name="label">Zip code:</ui:define> <h:inputText id="zip" value="#{location.zip}" required="true"> <a:support event="onblur" reRender="zipDecoration" bypassUpdates="true"/> </h:inputText> </s:decorate>

<h:commandButton/>

</h:form>

public class Location { private String name; private String zip; // Getters and setters for name

@NotNull @Length(max=6) @ZipCode(message="#{messages['location.zipCode.invalid']}") public String getZip() { return zip; } public void setZip(String z) { zip = z; }}

location.zipCode.invalid = The zip code is not valid for #{location.name}

Seam 2 Reference Guide

182

Page 188: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 12. GROOVY INTEGRATIONOne aspect of JBoss Seam is its RAD (Rapid Application Development) capability. While notsynonymous with RAD, one interesting tool in this space is dynamic languages. Until recently, choosinga dynamic language was required choosing a completely different development platform (adevelopment platform with a set of APIs and a runtime so great that you would no longer want to usethe old legacy Java [sic] APIs anymore). Dynamic languages built on top of the Java Virtual Machine,and Groovy in particular broke this approach in silos.

JBoss Seam now unites the dynamic language world with the Java EE world by seamlessly integratingboth static and dynamic languages. JBoss Seam allows the application developer to use the best toolfor the task, without context switching. Writing dynamic Seam components is exactly like writingregular Seam components; you use the same annotations, the same APIs, the same everything.

NOTE

Groovy integration in Seam is marked as technology preview, so standard support is notguaranteed.

12.1. GROOVY INTRODUCTION

Groovy is an agile dynamic language based on the Java language but with additional features inspiredby Python, Ruby and Smalltalk. The strengths of Groovy are twofold:

Java syntax is supported in Groovy: Java code is Groovy code, making the learning curve verysmooth

Groovy objects are Java objects, and Groovy classes are Java classes: Groovy integratessmoothly with existing Java libraries and frameworks.

12.2. WRITING SEAM APPLICATIONS IN GROOVY

Since a Groovy object is a Java object, you can virtually write any Seam component, or any class forwhat it worth, in Groovy and deploy it. You can also mix Groovy classes and Java classes in the sameapplication.

12.2.1. Writing Groovy components

As you should have noticed by now, Seam uses annotations heavily. Be sure to use Groovy 1.1 or abovefor annotation support. Here are some example of groovy code used in a Seam application.

12.2.1.1. Entity

@Entity @Name("hotel") class Hotel implements Serializable { @Id @GeneratedValue Long id

@Length(max=50) @NotNull String name

CHAPTER 12. GROOVY INTEGRATION

183

Page 189: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Groovy natively support the notion of properties (getter/setter), so there is no need to explicitly writeverbose getters and setters: in the previous example, the hotel class can be accessed from Java as hotel.getCity(), the getters and setters being generated by the Groovy compiler. This type ofsyntactic sugar makes the entity code very concise.

12.2.1.2. Seam component

Writing Seam components in Groovy is no different than in Java with annotations used to mark theclass as a Seam component.

@Length(max=100) @NotNull String address

@Length(max=40) @NotNull String city

@Length(min=2, max=10) @NotNull String state

@Length(min=4, max=6) @NotNull String zip

@Length(min=2, max=40) @NotNull String country

@Column(precision=6, scale=2) BigDecimal price

@Override String toString() { return "Hotel(${name},${address},${city},${zip})" } }

@Scope(ScopeType.SESSION)@Name("bookingList")class BookingListAction implements Serializable{ @In EntityManager em @In User user @DataModel List<Booking> bookings @DataModelSelection Booking booking @Logger Log log

@Factory public void getBookings() { bookings = em.createQuery(''' select b from Booking b where b.user.username = :username order by b.checkinDate''') .setParameter("username", user.username) .getResultList() } public void cancel()

Seam 2 Reference Guide

184

Page 190: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

12.2.2. seam-gen

seam-gen has a transparent integration with Groovy. You can write Groovy code in seam-gen backedprojects without any additional infrastructure requirement. When writing a Groovy entity, simply placeyour .groovy files in src/model. Unsurprisingly, when writing an action, simply place your .groovyfiles in src/action.

12.3. DEPLOYMENT

Deploying Groovy classes is very much like deploying Java classes (surprisingly, no need to write norcomply with a 3-letter composite specification to support a multi-language component framework).

Beyond standard deployments, JBoss Seam has the ability, at development time, to redeployJavaBeans Seam component classes without having to restart the application, saving a lot of time inthe development and test cycles. The same support is provided for GroovyBeans Seam componentswhen the .groovy files are deployed.

12.3.1. Deploying Groovy code

A Groovy class is a Java class, with a bytecode representation just like a Java class. To deploy, aGroovy entity, a Groovy Session bean or a Groovy Seam component, a compilation step is necessary. Acommon approach is to use the groovyc ant task. Once compiles, a Groovy class is in no way differentthan a Java class and the application server will treat them equally. Note that this allow a seamless mixof Groovy and Java code.

12.3.2. Native .groovy file deployment at development time

JBoss Seam natively supports the deployment of .groovy files (ie without compilation) in incrementalhotdeployment mode (development only). This enables a very fast edit/test cycle. To set up .groovydeployments, follow the configuration at Section 2.8, “Seam and incremental hot deployment” anddeploy your Groovy code (.groovy files) into the WEB-INF/dev directory. The GroovyBeancomponents will be picked up incrementally with no need to restart the application (and obviously notthe application server either).

Be aware that the native .groovy file deployment suffers the same limitations as the regular Seamhotdeployment:

The components must be JavaBeans or GroovyBeans. They cannot be EJB3 bean

Entities cannot be hotdeployed

The hot-deployable components will not be visible to any classes deployed outside of WEB-INF/dev

{ log.info("Cancel booking: #{bookingList.booking.id} for #{user.username}") Booking cancelled = em.find(Booking.class, booking.id) if (cancelled != null) em.remove( cancelled ) getBookings() FacesMessages.instance().add("Booking cancelled for confirmation number #{bookingList.booking.id}", new Object[0]) }}

CHAPTER 12. GROOVY INTEGRATION

185

Page 191: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam debug mode must be enabled

12.3.3. seam-gen

Seam-gen transparently supports Groovy files deployment and compilation. This includes the native .groovy file deployment in development mode (compilation-less). If you create a seam-gen project oftype WAR, Java and Groovy classes in src/action will automatically be candidate for theincremental hot deployment. If you are in production mode, the Groovy files will simply be compiledbefore deployment.

You will find a live example of the Booking demo written completely in Groovy and supportingincremental hot deployment in examples/groovybooking.

Seam 2 Reference Guide

186

Page 192: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 13. THE SEAM APPLICATION FRAMEWORKSeam makes it really easy to create applications by writing plain Java classes with annotations, whichdo not need to extend any special interfaces or superclasses. But we can simplify some commonprogramming tasks even further, by providing a set of pre-built components which can be re-usedeither by configuration in components.xml (for very simple cases) or extension.

The extremely simple Seam Application Framework can reduce the amount of code you need to writewhen doing basic database access in a web application, (using either Hibernate or JPA) with its simplecalsses that are easy to understand and extend.

13.1. INTRODUCTION

The components provided by the Seam application framework may be used in one of two differentapproaches. The first way is to install and configure an instance of the component in components.xml, just like we have done with other kinds of built-in Seam components. For example,the following fragment from components.xml installs a component which can perform basic CRUDoperations for a Person entity:

Seam components can also be extended instead if you do not with to deal with the above style ofcoding:

The second approach has one huge advantage: you can easily add extra functionality, and override thebuilt-in functionality (the framework classes were carefully designed for extension and customization).

A second advantage is that your classes may be EJB stateful session beans, if you like. (They do nothave to be, they can be plain JavaBean components if you prefer.) When you are using JBossEnterprise Application Platform:

<framework:entity-home name="personHome" entity-class="eg.Person" entity-manager="#{personDatabase}"> <framework:id>#{param.personId}</framework:id></framework:entity-home>

@Name("personHome")public class PersonHome extends EntityHome<Person> { @In EntityManager personDatabase; public EntityManager getEntityManager() { return personDatabase; } }

@Stateful@Name("personHome")public class PersonHome extends EntityHome<Person> implements LocalPersonHome { }

CHAPTER 13. THE SEAM APPLICATION FRAMEWORK

187

Page 193: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

You can also make your classes stateless session beans. In this case you must use injection to providethe persistence context, even if it is called entityManager:

At this time, the Seam Application Framework provides four main built-in components: EntityHomeand HibernateEntityHome for CRUD, along with EntityQuery and HibernateEntityQuery forqueries.

The Home and Query components are written so that they can function with a scope of session, eventor conversation. Which scope you use depends upon the state model you wish to use in yourapplication.

The Seam Application Framework only works with Seam-managed persistence contexts. By default,the components will look for a persistence context named entityManager.

13.2. HOME OBJECTS

A Home object provides persistence operations for a particular entity class. Suppose we have ourtrusty Person class:

We can define a personHome component either via configuration:

Or via extension:

A Home object provides the following operations: persist(), remove(), update() and getInstance(). Before you can call the remove(), or update() operations, you must first set theidentifier of the object you are interested in, using the setId() method.

@Stateless@Name("personHome")public class PersonHome extends EntityHome<Person> implements LocalPersonHome { @In EntityManager entityManager; public EntityManager getPersistenceContext() { entityManager; } }

@Entitypublic class Person { @Id private Long id; private String firstName; private String lastName; private Country nationality; //getters and setters...}

<framework:entity-home name="personHome" entity-class="eg.Person" />

@Name("personHome")public class PersonHome extends EntityHome<Person> {}

Seam 2 Reference Guide

188

Page 194: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We can use a Home directly from a JSF page, for example:

Usually, it is much nicer to be able to refer to the Person merely as person, so let us make thatpossible by adding a line to components.xml:

(If we are using configuration.) Or by adding a @Factory method to PersonHome:

(If we are using extension.) This change simplifies our JSF page to the following:

Well, those few lines of code allow us to create new Person entries. If we want to be able to display,update and delete pre-existing Person entries in the database, we need to be able to pass the entryidentifier to the PersonHome. Page parameters are a great way to do that:

<h1>Create Person</h1><h:form> <div>First name: <h:inputText value="#{personHome.instance.firstName}"/></div> <div>Last name: <h:inputText value="#{personHome.instance.lastName}"/></div> <div> <h:commandButton value="Create Person" action="#{personHome.persist}"/> </div></h:form>

<factory name="person" value="#{personHome.instance}"/>

<framework:entity-home name="personHome" entity-class="eg.Person" />

@Name("personHome")public class PersonHome extends EntityHome<Person> { @Factory("person") public Person initPerson() { return getInstance(); } }

<h1>Create Person</h1><h:form> <div>First name: <h:inputText value="#{person.firstName}"/></div> <div>Last name: <h:inputText value="#{person.lastName}"/></div> <div> <h:commandButton value="Create Person" action="#{personHome.persist}"/> </div></h:form>

<pages> <page view-id="/editPerson.jsp"> <param name="personId" value="#{personHome.id}"/>

CHAPTER 13. THE SEAM APPLICATION FRAMEWORK

189

Page 195: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We can add the extra operations to our JSF page:

When we link to the page with no request parameters, the page will be displayed as a Create Personpage. When we provide a value for the personId request parameter, it will be an Edit Person page.

Suppose we need to create Person entries with their nationality initialized. We can do that easily, viaconfiguration:

Or by extension:

</page></pages>

<h1> <h:outputText rendered="#{!personHome.managed}" value="Create Person"/> <h:outputText rendered="#{personHome.managed}" value="Edit Person"/></h1><h:form> <div>First name: <h:inputText value="#{person.firstName}"/></div> <div>Last name: <h:inputText value="#{person.lastName}"/></div> <div> <h:commandButton value="Create Person" action="#{personHome.persist}" rendered="#{!personHome.managed}"/> <h:commandButton value="Update Person" action="#{personHome.update}" rendered="#{personHome.managed}"/> <h:commandButton value="Delete Person" action="#{personHome.remove}" rendered="#{personHome.managed}"/> </div></h:form>

<factory name="person" value="#{personHome.instance}"/>

<framework:entity-home name="personHome" entity-class="eg.Person" new-instance="#{newPerson}"/>

<component name="newPerson" class="eg.Person"> <property name="nationality">#{country}</property></component>

@Name("personHome")public class PersonHome extends EntityHome<Person> { @In Country country; @Factory("person") public Person initPerson() { return getInstance(); } protected Person createInstance() { return new Person(country);

Seam 2 Reference Guide

190

Page 196: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Of course, the Country could be an object managed by another Home object, for example, CountryHome.

To add more sophisticated operations (association management, etc), we can just add methods to PersonHome.

The Home object raises an org.jboss.seam.afterTransactionSuccess event when atransaction succeeds (a call to persist(), update() or remove() succeeds). By observing thisevent we can refresh our queries when the underlying entities are changed. If we only want to refreshcertain queries when a particular entity is persisted, updated or removed we can observe the org.jboss.seam.afterTransactionSuccess.<name> event (where <name> is the name of theentity).

The Home object automatically displays faces messages when an operation is successful. Tocustomize these messages we can, again, use configuration:

} }

@Name("personHome")public class PersonHome extends EntityHome<Person> { @In Country country; @Factory("person") public Person initPerson() { return getInstance(); } protected Person createInstance() { return new Person(country); } public void migrate() { getInstance().setCountry(country); update(); } }

<factory name="person" value="#{personHome.instance}"/>

<framework:entity-home name="personHome" entity-class="eg.Person" new-instance="#{newPerson}"> <framework:created-message>New person #{person.firstName} #{person.lastName} created</framework:created-message> <framework:deleted-message>Person #{person.firstName} #{person.lastName} deleted</framework:deleted-message> <framework:updated-message>Person #{person.firstName} #{person.lastName} updated</framework:updated-message></framework:entity-home>

<component name="newPerson"

CHAPTER 13. THE SEAM APPLICATION FRAMEWORK

191

Page 197: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Or extension:

But the best way to specify the messages is to put them in a resource bundle known to Seam (thebundle named messages, by default).

This enables internationalization, and keeps your code and configuration clean of presentationconcerns.

The final step is to add validation functionality to the page, using <s:validateAll> and <s:decorate>.

13.3. QUERY OBJECTS

If we need a list of all Person instance in the database, we can use a Query object. For example:

We can use it from a JSF page:

class="eg.Person"> <property name="nationality">#{country}</property></component>

@Name("personHome")public class PersonHome extends EntityHome<Person> { @In Country country; @Factory("person") public Person initPerson() { return getInstance(); } protected Person createInstance() { return new Person(country); } protected String getCreatedMessage() { return "New person #{person.firstName} #{person.lastName} created"; } protected String getUpdatedMessage() { return "Person #{person.firstName} #{person.lastName} updated"; } protected String getDeletedMessage() { return "Person #{person.firstName} #{person.lastName} deleted"; } }

Person_created=New person #{person.firstName} #{person.lastName} createdPerson_deleted=Person #{person.firstName} #{person.lastName} deletedPerson_updated=Person #{person.firstName} #{person.lastName} updated

<framework:entity-query name="people" ejbql="select p from Person p"/>

<h1>List of people</h1><h:dataTable value="#{people.resultList}" var="person"> <h:column> <s:link view="/editPerson.jsp" value="#{person.firstName} #{person.lastName}">

Seam 2 Reference Guide

192

Page 198: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We probably need to support pagination:

We will use a page parameter to determine the page to display:

The JSF code for a pagination control is a bit verbose, but manageable:

Real search screens let the user enter a bunch of optional search criteria to narrow the list of resultsreturned. The Query object lets you specify optional restrictions to support this important usecase:

<f:param name="personId" value="#{person.id}"/> </s:link> </h:column></h:dataTable>

<framework:entity-query name="people" ejbql="select p from Person p" order="lastName" max-results="20"/>

<pages> <page view-id="/searchPerson.jsp"> <param name="firstResult" value="#{people.firstResult}"/> </page></pages>

<h1>Search for people</h1><h:dataTable value="#{people.resultList}" var="person"> <h:column> <s:link view="/editPerson.jsp" value="#{person.firstName} #{person.lastName}"> <f:param name="personId" value="#{person.id}"/> </s:link> </h:column></h:dataTable>

<s:link view="/search.xhtml" rendered="#{people.previousExists}" value="First Page"> <f:param name="firstResult" value="0"/></s:link>

<s:link view="/search.xhtml" rendered="#{people.previousExists}" value="Previous Page"> <f:param name="firstResult" value="#{people.previousFirstResult}"/></s:link>

<s:link view="/search.xhtml" rendered="#{people.nextExists}" value="Next Page"> <f:param name="firstResult" value="#{people.nextFirstResult}"/></s:link>

<s:link view="/search.xhtml" rendered="#{people.nextExists}" value="Last Page"> <f:param name="firstResult" value="#{people.lastFirstResult}"/></s:link>

CHAPTER 13. THE SEAM APPLICATION FRAMEWORK

193

Page 199: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Notice the use of an example object.

To refresh the query when the underlying entities change we observe the org.jboss.seam.afterTransactionSuccess event:

Or, to just refresh the query when the person entity is persisted, updated or removed through PersonHome:

Unfortunately Query objects do not work well with join fetch queries—the use of pagination with thesequeries is not recommended, and you will have to implement your own method of calculating the totalnumber of results (by overriding getCountEjbql().

The examples in this section have all shown reuse by configuration. However, reuse by extension isequally possible for Query objects.

<component name="examplePerson" class="Person"/> <framework:entity-query name="people" ejbql="select p from Person p" order="lastName" max-results="20"> <framework:restrictions> <value>lower(firstName) like lower( concat(#{examplePerson.firstName},'%') )</value> <value>lower(lastName) like lower( concat(#{examplePerson.lastName},'%') )</value> </framework:restrictions></framework:entity-query>

<h1>Search for people</h1><h:form> <div>First name: <h:inputText value="#{examplePerson.firstName}"/></div> <div>Last name: <h:inputText value="#{examplePerson.lastName}"/></div> <div><h:commandButton value="Search" action="/search.jsp"/></div></h:form>

<h:dataTable value="#{people.resultList}" var="person"> <h:column> <s:link view="/editPerson.jsp" value="#{person.firstName} #{person.lastName}"> <f:param name="personId" value="#{person.id}"/> </s:link> </h:column></h:dataTable>

<event type="org.jboss.seam.afterTransactionSuccess"> <action execute="#{people.refresh}" /></event>

<event type="org.jboss.seam.afterTransactionSuccess.Person"> <action execute="#{people.refresh}" /> </event>

Seam 2 Reference Guide

194

Page 200: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

13.4. CONTROLLER OBJECTS

A totally optional part of the Seam Application Framework is the class Controller and its subclasses EntityController HibernateEntityController and BusinessProcessController. Theseclasses provide nothing more than some convenience methods for access to commonly used built-incomponents and methods of built-in components. They help save a few keystrokes and provide a greatlaunchpad for new users to explore the rich functionality built in to Seam.

For example, here is what RegisterAction from the Seam registration example would look like:

@Stateless@Name("register")public class RegisterAction extends EntityController implements Register{

@In private User user; public String register() { List existing = createQuery("select u.username from User u where u.username=:username") .setParameter("username", user.getUsername()) .getResultList(); if ( existing.size()==0 ) { persist(user); info("Registered new user #{user.username}"); return "/registered.jspx"; } else { addFacesMessage("User #{user.username} already exists"); return null; } }

}

CHAPTER 13. THE SEAM APPLICATION FRAMEWORK

195

Page 201: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 14. SEAM AND JBOSS RULESSeam makes it easy to call JBoss Rules (Drools) rulebases from Seam components or jBPM processdefinitions.

14.1. INSTALLING RULES

The first step is to make an instance of org.drools.RuleBase available in a Seam context variable.For testing purposes, Seam provides a built-in component that compiles a static set of rules from theclasspath. You can install this component via components.xml:

This component compiles rules from a set of .drl files and caches an instance of org.drools.RuleBase in the Seam APPLICATION context. Note that it is quite likely that you willneed to install multiple rule bases in a rule-driven application.

If you want to use a Drools DSL, you also need to specify the DSL definition:

In most rules-driven applications, rules need to be dynamically deployable, so a production applicationwill want to use a Drools RuleAgent to manage the RuleBase. The RuleAgent can connect to a Droolsrule server (BRMS) or hot deploy rules packages from a local file repository. The RulesAgent-managedRuleBase is also configurable in components.xml:

The properties file contains properties specific to the RulesAgent. Here is an example configurationfile from the Drools example distribution.

It is also possible to configure the options on the component directly, bypassing the configuration file.

<drools:rule-base name="policyPricingRules"> <drools:rule-files> <value>policyPricingRules.drl</value> </drools:rule-files></drools:rule-base>

<drools:rule-base name="policyPricingRules" dsl-file="policyPricing.dsl"> <drools:rule-files> <value>policyPricingRules.drl</value> </drools:rule-files></drools:rule-base>

<drools:rule-agent name="insuranceRules" configurationFile="/WEB-INF/deployedrules.properties" />

newInstance=trueurl=http://localhost:8080/drools-jbrms/org.drools.brms.JBRMS/package/org.acme.insurance/fmeyerlocalCacheDir=/Users/fernandomeyer/projects/jbossrules/drools-examples/drools-examples-brms/cachepoll=30name=insuranceconfig

<drools:rule-agent name="insuranceRules" url="http://localhost:8080/drools-

Seam 2 Reference Guide

196

Page 202: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Next, we need to make an instance of org.drools.WorkingMemory available to each conversation.(Each WorkingMemory accumulates facts relating to the current conversation.)

Notice that we gave the policyPricingWorkingMemory a reference back to our rule base via the ruleBase configuration property.

14.2. USING RULES FROM A SEAM COMPONENT

We can now inject our WorkingMemory into any Seam component, assert facts, and fire rules:

14.3. USING RULES FROM A JBPM PROCESS DEFINITION

You can even allow a rule base to act as a jBPM action handler, decision handler, or assignment handler—in either a pageflow or business process definition.

jbrms/org.drools.brms.JBRMS/package/org.acme.insurance/fmeyer" local-cache-dir="/Users/fernandomeyer/projects/jbossrules/drools-examples/drools-examples-brms/cache" poll="30" configuration-name="insuranceconfig" />

<drools:managed-working-memory name="policyPricingWorkingMemory" auto-create="true" rule-base="#{policyPricingRules}"/>

@In WorkingMemory policyPricingWorkingMemory;

@In Policy policy;@In Customer customer;

public void pricePolicy() throws FactException{ policyPricingWorkingMemory.assertObject(policy); policyPricingWorkingMemory.assertObject(customer); policyPricingWorkingMemory.fireAllRules();}

<decision name="approval"> <handler class="org.jboss.seam.drools.DroolsDecisionHandler"> <workingMemoryName>orderApprovalRulesWorkingMemory</workingMemoryName> <assertObjects> <element>#{customer}</element> <element>#{order}</element> <element>#{order.lineItems}</element> </assertObjects> </handler> <transition name="approved" to="ship"> <action class="org.jboss.seam.drools.DroolsActionHandler"> <workingMemoryName>shippingRulesWorkingMemory</workingMemoryName> <assertObjects>

CHAPTER 14. SEAM AND JBOSS RULES

197

Page 203: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The <assertObjects> element specifies EL expressions that return an object or collection of objectsto be asserted as facts into the WorkingMemory.

There is also support for using Drools for jBPM task assignments:

Certain objects are available to the rules as Drools globals, namely the jBPM Assignable, as assignable and a Seam Decision object, as decision. Rules which handle decisions should call decision.setOutcome("result") to determine the result of the decision. Rules which performassignments should set the actor id using the Assignable.

<element>#{customer}</element> <element>#{order}</element> <element>#{order.lineItems}</element> </assertObjects> </action> </transition> <transition name="rejected" to="cancelled"/> </decision>

<task-node name="review"> <task name="review" description="Review Order"> <assignment handler="org.jboss.seam.drools.DroolsAssignmentHandler"> <workingMemoryName>orderApprovalRulesWorkingMemory</workingMemoryName> <assertObjects> <element>#{actor}</element> <element>#{customer}</element> <element>#{order}</element> <element>#{order.lineItems}</element> </assertObjects> </assignment> </task> <transition name="rejected" to="cancelled"/> <transition name="approved" to="approved"/></task-node>

package org.jboss.seam.examples.shop

import org.jboss.seam.drools.Decision

global Decision decision

rule "Approve Order For Loyal Customer" when Customer( loyaltyStatus == "GOLD" ) Order( totalAmount <= 10000 ) then decision.setOutcome("approved");end

package org.jboss.seam.examples.shop

Seam 2 Reference Guide

198

Page 204: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

import org.jbpm.taskmgmt.exe.Assignable

global Assignable assignable

rule "Assign Review For Small Order" when Order( totalAmount <= 100 ) then assignable.setPooledActors( new String[] {"reviewers"} );end

CHAPTER 14. SEAM AND JBOSS RULES

199

Page 205: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 15. SECURITYThe Seam Security API is an optional Seam feature that provides authentication and authorizationfeatures for securing both domain and page resources within your Seam project.

15.1. OVERVIEW

Seam Security provides two different modes of operation:

simplified mode - this mode supports authentication services and simple role-based securitychecks.

advanced mode - this mode supports all the same features as the simplified mode, plus it offersrule-based security checks using JBoss Rules.

15.1.1. Which mode is right for my application?

That all depends on the requirements of your application. If you have minimal security requirements,for example if you only wish to restrict certain pages and actions to users who are logged in, or whobelong to a certain role, then the simplified mode will probably be sufficient. The advantages of this is amore simplified configuration, significantly less libraries to include, and a smaller memory footprint.

If on the other hand, your application requires security checks based on contextual state or complexbusiness rules, then you will require the features provided by the advanced mode.

15.2. REQUIREMENTS

If using the advanced mode features of Seam Security, the following jar files are required to beconfigured as modules in application.xml. If you are using Seam Security in simplified mode, theseare not required:

drools-compiler.jar

drools-core.jar

janino.jar

antlr-runtime.jar

mvel14.jar

For web-based security, jboss-seam-ui.jar must also be included in the application's war file.

15.3. DISABLING SECURITY

In some situations it may be necessary to disable Seam Security, for example during unit tests. Thiscan be done by calling the static method Identity.setSecurityEnabled(false) to disablesecurity checks. Doing this prevents any security checks being performed for the following:

Entity Security

Hibernate Security Interceptor

Seam Security Interceptor

Seam 2 Reference Guide

200

Page 206: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Page restrictions

15.4. AUTHENTICATION

The authentication features provided by Seam Security are built upon JAAS (Java Authentication andAuthorization Service), and as such provide a robust and highly configurable API for handling userauthentication. However, for less complex authentication requirements Seam offers a much moresimplified method of authentication that hides the complexity of JAAS.

15.4.1. Configuration

The simplified authentication method uses a built-in JAAS login module, SeamLoginModule, whichdelegates authentication to one of your own Seam components. This login module is alreadyconfigured inside Seam as part of a default application policy and as such does not require anyadditional configuration files. It allows you to write an authentication method using the entity classesthat are provided by your own application. Configuring this simplified form of authentication requiresthe identity component to be configured in components.xml:

If you wish to use the advanced security features such as rule-based permission checks, all you need todo is include the Drools (JBoss Rules) jars in your classpath, and add some additional configuration,described later.

The EL expression #{authenticator.authenticate} is a method binding indicating that the authenticate method of the authenticator component will be used to authenticate the user.

15.4.2. Writing an authentication method

The authenticate-method property specified for identity in components.xml specifies whichmethod will be used by SeamLoginModule to authenticate users. This method takes no parameters,and is expected to return a boolean indicating whether authentication is successful or not. The user'susername and password can be obtained from Identity.instance().getUsername() and Identity.instance().getPassword(), respectively. Any roles that the user is a member ofshould be assigned using Identity.instance().addRole(). Here's a complete example of anauthentication method inside a JavaBean component:

<components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core" xmlns:security="http://jboss.com/products/seam/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd http://jboss.com/products/seam/security http://jboss.com/products/seam/security-2.1.xsd">

<security:identity authenticate-method="#{authenticator.authenticate}"/>

</components>

@Name("authenticator")public class Authenticator { @In EntityManager entityManager;

CHAPTER 15. SECURITY

201

Page 207: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

In the above example, both User and UserRole are application-specific entity beans. The rolesparameter is populated with the roles that the user is a member of, which should be added to the Setas literal string values, for example admin, user. In this case, if the user record is not found and a NoResultException thrown, the authentication method returns false to indicate theauthentication failed.

15.4.2.1. Identity.addRole()

The Identity.addRole() method behaves differently depending on whether the current session isauthenticated or not. If the session is not authenticated, then addRole() should only be called duringthe authentication process. When called here, the role name is placed into a temporary list of pre-authenticated roles. Once authentication is successful, the pre-authenticated roles then become realroles, and calling Identity.hasRole() for those roles will then return true. The following sequencediagram represents the list of pre-authenticated roles as a first class object to show more clearly how itfits in to the authentication process.

public boolean authenticate() { try { User user = (User) entityManager.createQuery( "from User where username = :username and password = :password") .setParameter("username", Identity.instance().getUsername()) .setParameter("password", Identity.instance().getPassword()) .getSingleResult();

if (user.getRoles() != null) { for (UserRole mr : user.getRoles()) Identity.instance().addRole(mr.getName()); }

return true; } catch (NoResultException ex) { return false; }

}

}

Seam 2 Reference Guide

202

Page 208: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

15.4.2.2. Special Considerations

When writing an authenticator method, it is important that it is kept minimal and free from any side-effects. This is because there is no guarantee as to how many times the authenticator method will becalled by the security API, and as such it may be invoked multiple times during a single request.Because of this, any special code that should execute upon a successful or failed authentication shouldbe written by implementing an event observer. See the section on Security Events further down in thischapter for more information about which events are raised by Seam Security.

To give an example, let us say that upon a successful login that some user statistics must be updated.We would do this by writing an event observer for the org.jboss.seam.security.loginSuccessful event, like this:

15.4.3. Writing a login form

The Identity component provides both username and password properties, catering for the mostcommon authentication scenario. These properties can be bound directly to the username andpassword fields on a login form. Once these properties are set, calling the identity.login()method will authenticate the user using the provided credentials. Here's an example of a simple loginform:

@In UserStats userStats;

@Observer("org.jboss.seam.security.loginSuccessful") public void updateUserStats() { userStats.setLastLoginDate(new Date()); userStats.incrementLoginCount(); }

<div> <h:outputLabel for="name" value="Username"/>

CHAPTER 15. SECURITY

203

Page 209: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Similarly, logging out the user is done by calling #{identity.logout}. Calling this action will clearthe security state of the currently authenticated user.

15.4.4. Simplified Configuration - Summary

So to sum up, there are the three easy steps to configure authentication:

Configure an authentication method in components.xml.

Write an authentication method.

Write a login form so that the user can authenticate.

15.4.5. Handling Security Exceptions

To prevent users from receiving the default error page in response to a security error, it isrecommended that pages.xml is configured to redirect security errors to a more elegant page. Thetwo main types of exceptions thrown by the security API are:

NotLoggedInException - This exception is thrown if the user attempts to access arestricted action or page when they are not logged in.

AuthorizationException - This exception is only thrown if the user is already logged in,and they have attempted to access a restricted action or page for which they do not have thenecessary privileges.

In the case of a NotLoggedInException, it is recommended that the user is redirected to either alogin or registration page so that they can log in. For an AuthorizationException, it may be usefulto redirect the user to an error page. Here's an example of a pages.xml file that redirects both ofthese security exceptions:

<h:inputText id="name" value="#{identity.username}"/></div>

<div> <h:outputLabel for="password" value="Password"/> <h:inputSecret id="password" value="#{identity.password}"/></div>

<div> <h:commandButton value="Login" action="#{identity.login}"/></div>

<pages>

...

<exception class="org.jboss.seam.security.NotLoggedInException"> <redirect view-id="/login.xhtml"> <message>You must be logged in to perform this action</message> </redirect> </exception>

<exception class="org.jboss.seam.security.AuthorizationException">

Seam 2 Reference Guide

204

Page 210: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Most web applications require even more sophisticated handling of login redirection, so Seam includessome special functionality for handling this problem.

15.4.6. Login Redirection

You can ask Seam to redirect the user to a login screen when an unauthenticated user tries to access aparticular view (or wildcarded view-id) as follows:

(This is less of a blunt instrument than the exception handler shown above, but should probably be usedin conjunction with it.)

After the user logs in, we want to automatically send them back where they came from, so they canretry the action that required logging in. If you add the following event listeners to components.xml,attempts to access a restricted view while not logged in will be remembered, so that upon the usersuccessfully logging in they will be redirected to the originally requested view, with any pageparameters that existed in the original request.

Note that login redirection is implemented as a conversation-scoped mechanism, so don't end theconversation in your authenticate() method.

15.4.7. HTTP Authentication

Although not recommended for use unless absolutely necessary, Seam provides means forauthenticating using either HTTP Basic or HTTP Digest (RFC 2617) methods. To use either form ofauthentication, the authentication-filter component must be enabled in components.xml:

<end-conversation/> <redirect view-id="/security_error.xhtml"> <message>You do not have the necessary security privileges to perform this action.</message> </redirect> </exception>

</pages>

<pages login-view-id="/login.xhtml">

<page view-id="/members/*" login-required="true"/>

...

</pages>

<event type="org.jboss.seam.security.notLoggedIn"> <action execute="#{redirect.captureCurrentView}"/></event>

<event type="org.jboss.seam.security.postAuthenticate"> <action execute="#{redirect.returnToCapturedView}"/></event>

<web:authentication-filter url-pattern="*.seam" auth-type="basic"/>

CHAPTER 15. SECURITY

205

Page 211: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

To enable the filter for basic authentication, set auth-type to basic, or for digest authentication, setit to digest. If using digest authentication, the key and realm must also be set:

The key can be any String value. The realm is the name of the authentication realm that is presentedto the user when they authenticate.

15.4.7.1. Writing a Digest Authenticator

If using digest authentication, your authenticator class should extend the abstract class org.jboss.seam.security.digest.DigestAuthenticator, and use the validatePassword() method to validate the user's plain text password against the digest request.Here is an example:

15.4.8. Advanced Authentication Features

This section explores some of the advanced features provided by the security API for addressing morecomplex security requirements.

15.4.8.1. Using your container's JAAS configuration

If you would rather not use the simplified JAAS configuration provided by the Seam Security API, youmay instead delegate to the default system JAAS configuration by providing a jaas-config-nameproperty in components.xml. For example, if you are using JBoss AS and wish to use the otherpolicy (which uses the UsersRolesLoginModule login module provided by JBoss AS), then the entryin components.xml would look like this:

Keep in mind that doing this does not mean that your user will be authenticated in whichever containeryour Seam application is deployed in. It merely instructs Seam Security to authenticate itself using theconfigured JAAS security policy.

<web:authentication-filter url-pattern="*.seam" auth-type="digest" key="AA3JK34aSDlkj" realm="My App"/>

public boolean authenticate() { try { User user = (User) entityManager.createQuery( "from User where username = :username") .setParameter("username", identity.getUsername()) .getSingleResult();

return validatePassword(user.getPassword()); } catch (NoResultException ex) { return false; } }

<security:identity jaas-config-name="other"/>

Seam 2 Reference Guide

206

Page 212: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

15.5. ERROR MESSAGES

The security API produces a number of default faces messages for various security-related events. Thefollowing table lists the message keys that can be used to override these messages by specifying themin a message.properties resource file. To suppress the message, just put the key with an emptyvalue in the resource file.

Table 15.1. Security Message Keys

Message Key Description

org.jboss.seam.loginSuccessful This message is produced when a user successfullylogs in via the security API.

org.jboss.seam.loginFailed This message is produced when the login processfails, either because the user provided an incorrectusername or password, or because authenticationfailed in some other way.

org.jboss.seam.NotLoggedIn This message is produced when a user attempts toperform an action or access a page that requires asecurity check, and the user is not currentlyauthenticated.

org.jboss.seam.AlreadyLoggedIn This message is produced when a user that isalready authenticated attempts to log in again.

15.6. AUTHORIZATION

There are a number of authorization features provided by the Seam Security API for securing access tocomponents, component methods, and pages. This section describes each of these. An important thingto note is that if you wish to use any of the advanced features (such as rule-based permissions) thenyour components.xml must be configured to support this - see the Configuration section above.

15.6.1. Core concepts

Each of the authorization mechanisms provided by the Seam Security API are built upon the concept ofa user being granted roles and/or permissions. A role is a group, or type, of user that may have beengranted certain privileges for performing one or more specific actions within an application. Apermission on the other hand is a privilege (sometimes once-off) for performing a single, specificaction. It is entirely possible to build an application using nothing but permissions, however roles offera higher level of convenience when granting privileges to groups of users.

Roles are simple, consisting of only a name such as admin, user, customer, etc. Permissions consist ofboth a name and an action, and are represented within this documentation in the form name:action,for example customer:delete, or customer:insert.

15.6.2. Securing components

Let us start by examining the simplest form of authorization, component security, starting with the @Restrict annotation.

15.6.2.1. The @Restrict annotation

CHAPTER 15. SECURITY

207

Page 213: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam components may be secured either at the method or the class level, using the @Restrictannotation. If both a method and it's declaring class are annotated with @Restrict, the methodrestriction will take precedence (and the class restriction will not apply). If a method invocation fails asecurity check, then an exception will be thrown as per the contract for Identity.checkRestriction() (see Inline Restrictions). A @Restrict on just the componentclass itself is equivalent to adding @Restrict to each of its methods.

An empty @Restrict implies a permission check of componentName:methodName. Take for examplethe following component method:

In this example, the implied permission required to call the delete() method is account:delete.The equivalent of this would be to write @Restrict("#{s:hasPermission('account','delete',null)}"). Now let's look at another example:

This time, the component class itself is annotated with @Restrict. This means that any methodswithout an overriding @Restrict annotation require an implicit permission check. In the case of thisexample, the insert() method requires a permission of account:insert, while the delete()method requires that the user is a member of the admin role.

Before we go any further, let's address the #{s:hasRole()} expression seen in the above example.Both s:hasRole and s:hasPermission are EL functions, which delegate to the correspondinglynamed methods of the Identity class. These functions can be used within any EL expressionthroughout the entirety of the security API.

Being an EL expression, the value of the @Restrict annotation may reference any objects that existwithin a Seam context. This is extremely useful when performing permission checks for a specificobject instance. Look at this example:

@Name("account")public class AccountAction { @Restrict public void delete() { ... }}

@Restrict @Name("account")public class AccountAction { public void insert() { ... } @Restrict("#{s:hasRole('admin')}") public void delete() { ... }}

@Name("account")public class AccountAction { @In Account selectedAccount; @Restrict("#{s:hasPermission('account','modify',selectedAccount)}") public void modify() { selectedAccount.modify(); }}

Seam 2 Reference Guide

208

Page 214: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The interesting thing to note from this example is the reference to selectedAccount seen within thehasPermission() function call. The value of this variable will be looked up from within the Seamcontext, and passed to the hasPermission() method in Identity, which in this case can thendetermine if the user has the required permission for modifying the specified Account object.

15.6.2.2. Inline restrictions

Sometimes it might be desirable to perform a security check in code, without using the @Restrictannotation. In this situation, simply use Identity.checkRestriction() to evaluate a securityexpression, like this:

If the expression specified doesn't evaluate to true, either

if the user is not logged in, a NotLoggedInException exception is thrown or

if the user is logged in, an AuthorizationException exception is thrown.

It is also possible to call the hasRole() and hasPermission() methods directly from Java code:

15.6.3. Security in the user interface

One indication of a well designed user interface is that the user is not presented with options for whichthey don't have the necessary privileges to use. Seam Security allows conditional rendering of either 1)sections of a page or 2) individual controls, based upon the privileges of the user, using the very sameEL expressions that are used for component security.

Let's take a look at some examples of interface security. First of all, let's pretend that we have a loginform that should only be rendered if the user is not already logged in. Using the identity.isLoggedIn() property, we can write this:

If the user isn't logged in, then the login form will be rendered - very straight forward so far. Now let'spretend there is a menu on the page that contains some actions which should only be accessible tousers in the manager role. Here's one way that these could be written:

public void deleteCustomer() { Identity.instance().checkRestriction("#{s:hasPermission('customer','delete',selectedCustomer)}");}

if (!Identity.instance().hasRole("admin")) throw new AuthorizationException("Must be admin to perform this action");

if (!Identity.instance().hasPermission("customer", "create", null)) throw new AuthorizationException("You may not create new customers");

<h:form class="loginForm" rendered="#{not identity.loggedIn}">

<h:outputLink action="#{reports.listManagerReports}" rendered="#{s:hasRole('manager')}"> Manager Reports</h:outputLink>

CHAPTER 15. SECURITY

209

Page 215: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This is also quite straight forward. If the user is not a member of the manager role, then the outputLinkwill not be rendered. The rendered attribute can generally be used on the control itself, or on asurrounding <s:div> or <s:span> control.

Now for something more complex. Let us say you have a h:dataTable control on a page listingrecords for which you may or may not wish to render action links depending on the user's privileges.The s:hasPermission EL function allows us to pass in an object parameter which can be used todetermine whether the user has the requested permission for that object or not. Here's how adataTable with secured links might look:

15.6.4. Securing pages

Page security requires that the application is using a pages.xml file, however is extremely simple toconfigure. Simply include a <restrict/> element within the page elements that you wish to secure.If no explicit restriction is specified by the restrict element, an implied permission of /viewId.xhtml:render will be checked when the page is accessed via a non-faces (GET) request,and a permission of /viewId.xhtml:restore will be required when any JSF postback (formsubmission) originates from the page. Otherwise, the specified restriction will be evaluated as astandard security expression. Here's a couple of examples:

This page has an implied permission of /settings.xhtml:render required for non-faces requestsand an implied permission of /settings.xhtml:restore for faces requests.

Both faces and non-faces requests to this page require that the user is a member of the admin role.

15.6.5. Securing Entities

<h:dataTable value="#{clients}" var="cl"> <h:column> <f:facet name="header">Name</f:facet> #{cl.name} </h:column> <h:column> <f:facet name="header">City</f:facet> #{cl.city} </h:column> <h:column> <f:facet name="header">Action</f:facet> <s:link value="Modify Client" action="#{clientAction.modify}" rendered="#{s:hasPermission('client','modify',cl)"/> <s:link value="Delete Client" action="#{clientAction.delete}" rendered="#{s:hasPermission('client','delete',cl)"/> </h:column></h:dataTable>

<page view-id="/settings.xhtml"> <restrict/></page>

<page view-id="/reports.xhtml"> <restrict>#{s:hasRole('admin')}</restrict></page>

Seam 2 Reference Guide

210

Page 216: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam security also makes it possible to apply security restrictions to read, insert, update and deleteactions for entities.

To secure all actions for an entity class, add a @Restrict annotation on the class itself:

If no expression is specified in the @Restrict annotation, the default security check that is performedis a permission check of entityName:action, where entityName is the Seam component name ofthe entity (or the fully-qualified class name if no @Name is specified), and the action is either read, insert, update or delete.

It is also possible to only restrict certain actions, by placing a @Restrict annotation on the relevententity lifecycle method (annotated as follows):

@PostLoad - Called after an entity instance is loaded from the database. Use this method toconfigure a read permission.

@PrePersist - Called before a new instance of the entity is inserted. Use this method toconfigure an insert permission.

@PreUpdate - Called before an entity is updated. Use this method to configure an updatepermission.

@PreRemove - Called before an entity is deleted. Use this method to configure a deletepermission.

Here is an example of how an entity would be configured to perform a security check for any insertoperations. Please note that the method is not required to do anything, the only important thing inregard to security is how it is annotated:

@Entity@Name("customer")@Restrictpublic class Customer { ...}

@PrePersist @Restrict public void prePersist() {}

CHAPTER 15. SECURITY

211

Page 217: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

NOTE

You can also specify the call back method in /META-INF/orm.xml:

Of course, you still need to annotate the prePersist() method on Customer with @Restrict

And here is an example of an entity permission rule that checks if the authenticated user is allowed toinsert a new MemberBlog record (from the seamspace example). The entity for which the securitycheck is being made is automatically inserted into the working memory (in this case MemberBlog):

This rule will grant the permission memberBlog:insert if the currently authenticated user (indicatedby the Principal fact) has the same name as the member for which the blog entry is being created.The "principalName : name" structure that can be seen in the Principal fact (and other places)is a variable binding - it binds the name property of the Principal to a variable called principalName. Variable bindings allow the value to be referred to in other places, such as thefollowing line which compares the member's username to the Principal name. For more details,please refer to the JBoss Rules documentation.

Finally, we need to install a listener class that integrates Seam security with your JPA provider.

15.6.5.1. Entity security with JPA

Security checks for EJB3 entity beans are performed with an EntityListener. You can install thislistener by using the following META-INF/orm.xml file:

<?xml version="1.0" encoding="UTF-8"?><entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">

<entity class="Customer"> <pre-persist method-name="prePersist" /> </entity>

</entity-mappings>

rule InsertMemberBlog no-loop activation-group "permissions"when check: PermissionCheck(name == "memberBlog", action == "insert", granted == false) Principal(principalName : name) MemberBlog(member : member -> (member.getUsername().equals(principalName)))then check.grant();end;

Seam 2 Reference Guide

212

Page 218: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

15.6.5.2. Entity security with a Managed Hibernate Session

If you are using a Hibernate SessionFactory configured via Seam, and are using annotations, or orm.xml, then you don't need to do anything special to use entity security.

15.7. WRITING SECURITY RULES

Up to this point there has been a lot of mention of permissions, but no information about howpermissions are actually defined or granted. This section completes the picture, by explaining howpermission checks are processed, and how to implement permission checks for a Seam application.

15.7.1. Permissions Overview

So how does the security API know whether a user has the customer:modify permission for aspecific customer? Seam Security provides quite a novel method for determining user permissions,based on JBoss Rules. A couple of the advantages of using a rule engine are 1) a centralized locationfor the business logic that is behind each user permission, and 2) speed - JBoss Rules uses veryefficient algorithms for evaluating large numbers of complex rules involving multiple conditions.

15.7.2. Configuring a rules file

Seam Security expects to find a RuleBase component called securityRules which it uses toevaluate permission checks. This is configured in components.xml as follows:

<?xml version="1.0" encoding="UTF-8"?><entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">

<persistence-unit-metadata> <persistence-unit-defaults> <entity-listeners> <entity-listener class="org.jboss.seam.security.EntitySecurityListener"/> </entity-listeners> </persistence-unit-defaults> </persistence-unit-metadata>

</entity-mappings>

<components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core" xmlns:security="http://jboss.com/products/seam/security" xmlns:drools="http://jboss.com/products/seam/drools" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://jboss.com/products/seam/core http://jboss.com/products/seam/core-2.1.xsd http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd

CHAPTER 15. SECURITY

213

Page 219: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Once the RuleBase component is configured, it is time to write the security rules.

15.7.3. Creating a security rules file

For this step you need to create a file called security.drl in the /META-INF directory of yourapplication's jar file. In actual fact this file can be called anything you want, and exist in any location aslong as it is configured appropriately in components.xml.

So what should the security rules file contain? At this stage it might be a good idea to at least skimthrough the JBoss Rules documentation, however to get started here's an extremely simple example:

Let's break this down. The first thing we see is the package declaration. A package in JBoss Rules isessentially a collection of rules. The package name can be anything you want - it doesn't relate toanything else outside the scope of the rule base.

The next thing we can notice is a couple of import statements for the PermissionCheck and Roleclasses. These imports inform the rules engine that we'll be referencing these classes within our rules.

Finally we have the code for the rule. Each rule within a package should be given a unique name(usually describing the purpose of the rule). In this case our rule is called CanUserDeleteCustomersand will be used to check whether a user is allowed to delete a customer record.

Looking at the body of the rule definition we can notice two distinct sections. Rules have what isknown as a left hand side (LHS) and a right hand side (RHS). The LHS consists of the conditional part ofthe rule, for instance, a list of conditions which must be satisfied for the rule to fire. The LHS isrepresented by the when section. The RHS is the consequence, or action section of the rule that willonly be fired if all of the conditions in the LHS are met. The RHS is represented by the then section.The end of the rule is denoted by the end; line.

http://jboss.com/products/seam/drools http://jboss.com/products/seam/drools-2.1.xsd" http://jboss.com/products/seam/security http://jboss.com/products/seam/security-2.1.xsd">

<drools:rule-base name="securityRules"> <drools:rule-files> <value>/META-INF/security.drl</value> </drools:rule-files> </drools:rule-base>

</components>

package MyApplicationPermissions;

import org.jboss.seam.security.PermissionCheck;import org.jboss.seam.security.Role;

rule CanUserDeleteCustomerswhen c: PermissionCheck(name == "customer", action == "delete") Role(name == "admin")then c.grant();end;

Seam 2 Reference Guide

214

Page 220: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If we look at the LHS of the rule, we see two conditions listed there. Let's examine the first condition:

In plain English, this condition is stating that there must exist a PermissionCheck object with a nameproperty equal to "customer", and an action property equal to "delete" within the working memory.

So what is the working memory? Also known as a stateful session in Drools terminology, the workingmemory is a session-scoped object that contains the contextual information that is required by therules engine to make a decision about a permission check. Each time the hasPermission() methodis called, a temporary PermissionCheck object, or Fact, is inserted into the working memory. This PermissionCheck corresponds exactly to the permission that is being checked, so for example if youcall hasPermission("account", "create", null) then a PermissionCheck object with a name equal to "account" and action equal to "create" will be inserted into the working memory forthe duration of the permission check.

Besides the PermissionCheck facts, there is also a org.jboss.seam.security.Role fact foreach of the roles that the authenticated user is a member of. These Role facts are synchronized withthe user's authenticated roles at the beginning of every permission check. As a consequence, any Roleobject that is inserted into the working memory during the course of a permission check will beremoved before the next permission check occurs, if the authenticated user is not a member of thatrole. Besides the PermissionCheck and Role facts, the working memory also contains the java.security.Principal object that was created during the authentication process.

It is also possible to insert additional long-lived facts into the working memory by calling ((RuleBasedIdentity) RuleBasedIdentity.instance()).getSecurityContext().insert(), passing the object as aparameter. The exception to this is Role objects, which as already discussed are synchronized at thestart of each permission check.

Getting back to our simple example, we can also notice that the first line of our LHS is prefixed with c:.This is a variable binding, and is used to refer back to the object that is matched by the condition.Moving onto the second line of our LHS, we see this:

This condition simply states that there must be a Role object with a name of "admin" within theworking memory. As mentioned, user roles are inserted into the working memory at the beginning ofeach permission check. So, putting both conditions together, this rule is essentially saying "I will fire ifyou are checking for the customer:delete permission and the user is a member of the admin role".

So what is the consequence of the rule firing? Let us take a look at the RHS of the rule:

The RHS consists of Java code, and in this case is invoking the grant() method of the c object, whichas already mentioned is a variable binding for the PermissionCheck object. Besides the name and action properties of the PermissionCheck object, there is also a granted property which isinitially set to false. Calling grant() on a PermissionCheck sets the granted property to true,which means that the permission check was successful, allowing the user to carry out whatever actionthe permission check was intended for.

15.7.3.1. Wildcard permission checks

c: PermissionCheck(name == "customer", action == "delete")

Role(name == "admin")

c.grant()

CHAPTER 15. SECURITY

215

Page 221: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

It is possible to implement a wildcard permission check (which allows all actions for a given permissionname), by omitting the action constraint for the PermissionCheck in your rule, like this:

This rule allows users with the admin role to perform any action for any customer permission check.

15.8. SSL SECURITY

Seam includes basic support for serving sensitive pages via the HTTPS protocol. This is easilyconfigured by specifying a scheme for the page in pages.xml. The following example shows how theview /login.xhtml is configured to use HTTPS:

This configuration is automatically extended to both s:link and s:button JSF controls, which(when specifying the view) will also render the link using the correct protocol. Based on the previousexample, the following link will use the HTTPS protocol because /login.xhtml is configured to useit:

Browsing directly to a view when using the incorrect protocol will cause a redirect to the same viewusing the correct protocol. For example, browsing to a page that has scheme="https" using HTTP willcause a redirect to the same page using HTTPS.

It is also possible to configure a default scheme for all pages. This is useful if you wish to use HTTPS fora only few pages. If no default scheme is specified then the normal behavior is to continue use thecurrent scheme. So once the user accessed a page that required HTTPS, then HTTPS would continue tobe used after the user navigated away to other non-HTTPS pages. (While this is good for security, it isnot so great for performance!). To define HTTP as the default scheme, add this line to pages.xml:

Of course, if none of the pages in your application use HTTPS then it is not required to specify a defaultscheme.

You may configure Seam to automatically invalidate the current HTTP session each time the schemechanges. Just add this line to components.xml:

This option helps make your system less vulnerable to sniffing of the session id or leakage of sensitivedata from pages using HTTPS to other pages using HTTP.

15.9. CAPTCHA

rule CanDoAnythingToCustomersIfYouAreAnAdminwhen c: PermissionCheck(name == "customer") Role(name == "admin")then c.grant();end;

<page view-id="/login.xhtml" scheme="https"/>

<s:link view="/login.xhtml" value="Login"/>

<page view-id="*" scheme="http" />

<core:servlet-session invalidate-on-scheme-change="true"/>

Seam 2 Reference Guide

216

Page 222: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Though strictly not part of the security API, Seam provides a built-in CAPTCHA (CompletelyAutomated Public Turing test to tell Computers and Humans Apart) algorithm to prevent automatedprocesses from interacting with your application.

15.9.1. Configuring the CAPTCHA Servlet

To get up and running, it is necessary to configure the Seam Resource Servlet, which will provide theCaptcha challenge images to your pages. This requires the following entry in web.xml:

15.9.2. Adding a CAPTCHA to a form

Adding a CAPTCHA challenge to a form is extremely easy. Here's an example:

That's all there is to it. The graphicImage control displays the CAPTCHA challenge, and the inputText receives the user's response. The response is automatically validated against theCAPTCHA when the form is submitted.

15.9.3. Customizing the CAPTCHA algorithm

You may customize the CAPTCHA algorithm by overriding the built-in component:

<servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class></servlet>

<servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern></servlet-mapping>

<h:graphicImage value="/seam/resource/captcha"/><h:inputText id="verifyCaptcha" value="#{captcha.response}" required="true"> <s:validate /></h:inputText><h:message for="verifyCaptcha"/>

@Name("org.jboss.seam.captcha")@Scope(SESSION)public class HitchhikersCaptcha extends Captcha{ @Override @Create public void init() { setChallenge("What is the answer to life, the universe and everything?"); setCorrectResponse("42"); }

@Override public BufferedImage renderChallenge() {

CHAPTER 15. SECURITY

217

Page 223: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

15.10. SECURITY EVENTS

The following table describes a number of events (see Chapter 7, Events, interceptors and exceptionhandling) raised by Seam Security.

Table 15.2. Security Events

Event Key Description

org.jboss.seam.security.loginSuccessful

Raised when a login attempt is successful.

org.jboss.seam.security.loginFailed Raised when a login attempt fails.

org.jboss.seam.security.alreadyLoggedIn

Raised when a user that is already authenticatedattempts to log in again.

org.jboss.seam.security.notLoggedIn Raised when a security check fails when the user isnot logged in.

org.jboss.seam.security.notAuthorized

Raised when a security check fails when the user islogged in however doesn't have sufficient privileges.

org.jboss.seam.security.preAuthenticate

Raised just prior to user authentication.

org.jboss.seam.security.postAuthenticate

Raised just after user authentication.

org.jboss.seam.security.loggedOut Raised after the user has logged out.

org.jboss.seam.security.credentialsUpdated

Raised when the user's credentials have beenchanged.

org.jboss.seam.security.rememberMe Raised when the Identity's rememberMe property ischanged.

15.11. RUN AS

Sometimes it may be necessary to perform certain operations with elevated privileges, such ascreating a new user account as an unauthenticated user. Seam Security supports such a mechanism viathe RunAsOperation class. This class allows either the Principal or Subject, or the user's roles tobe overridden for a single set of operations.

BufferedImage img = super.renderChallenge(); img.getGraphics().drawOval(5, 3, 60, 14); //add an obscuring decoration return img; }}

Seam 2 Reference Guide

218

Page 224: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The following code example demonstrates how RunAsOperation is used, by overriding its getRoles() method to specify a set of roles to masquerade as for the duration of the operation. The execute() method contains the code that will be executed with the elevated privileges.

In a similar way, the getPrincipal() or getSubject() methods can also be overridden to specifythe Principal and Subject instances to use for the duration of the operation. Finally, the run()method is used to carry out the RunAsOperation.

15.12. EXTENDING THE IDENTITY COMPONENT

Sometimes it might be necessary to extend the Identity component if your application has specialsecurity requirements. For example, users might be required to authenticate using a Company orDepartment ID, along with their usual username and password. If permission-based security is requiredthen RuleBasedIdentity should be extended, otherwise Identity should be extended.

The following example shows an extended Identity component with an additional companyCode field.The install precedence of APPLICATION ensures that this extended Identity gets installed inpreference to the built-in Identity.

new RunAsOperation() { @Override public String[] getRoles() { return new String[] { "admin" }; } public void execute() { executePrivilegedOperation(); } }.run();

@Name("org.jboss.seam.security.identity")@Scope(SESSION)@Install(precedence = APPLICATION)@BypassInterceptors@Startuppublic class CustomIdentity extends Identity{ private static final LogProvider log = Logging.getLogProvider(CustomIdentity.class);

private String companyCode;

public String getCompanyCode() { return companyCode; }

public void setCompanyCode(String companyCode) { this.companyCode = companyCode; }

@Override public String login() {

CHAPTER 15. SECURITY

219

Page 225: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

log.info("###### CUSTOM LOGIN CALLED ######"); return super.login(); }}

Seam 2 Reference Guide

220

Page 226: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 16. INTERNATIONALIZATION, LOCALIZATION ANDTHEMESSeam makes it easy to build internationalized applications. First, let us walk through all the stagesneeded to internationalize and localize your application and then we will take a look at thecomponents Seam bundles.

16.1. INTERNATIONALIZING YOUR APP

A JEE application consists of many components and all of them must be configured properly for yourapplication to be localized.

Starting at the bottom, the first step is to ensure that your database server and client is using thecorrect character encoding for your locale. Normally you will want to use UTF-8. How to do this isoutside the scope of this tutorial.

16.1.1. Application server configuration

To ensure that the application server receives the request parameters in the correct encoding fromclient requests you have to configure the tomcat connector. If you use Tomcat or JBoss AS, add the URIEncoding="UTF-8" attribute to the connector configuration. For JBoss EAP AS 4.3 change ${JBOSS_HOME}/server/production/deploy/jboss-web.deployer/server.xml:

There is alternative which is probably better. You can tell JBoss AS that the encoding for the requestparameters will be taken from the request:

16.1.2. Translated application strings

You will also need localized strings for all the messages in your application (for example field labels onyour views). First you need to ensure that your resource bundle is encoded using the desired characterencoding. By default ASCII is used. Although ASCII is enough for many languages, it doesn't providecharacters for all languages.

Resource bundles must be created in ASCII, or use Unicode escape codes to represent Unicodecharacters. Since you do not compile a property file to byte code, there is no way to tell the JVM whichcharacter set to use. So you must use either ASCII characters or escape characters not in the ASCIIcharacter set. You can represent a Unicode character in any Java file using \uXXXX, where XXXX is thehexadecimal representation of the character.

You can write your translation of labels to your messages resource bundle in the native encoding andthen convert the content of the file into the escaped format through the tool native2ascii providedin the JDK. This tool will convert a file written in your native encoding to one that represents non-ASCIIcharacters as Unicode escape sequences.

Usage of this tool is described here for Java 5 or here for Java 6 . For example, to convert a file fromUTF-8:

<Connector port="8080" URIEncoding="UTF-8"/>

<Connector port="8080" useBodyEncodingForURI="true"/>

$ native2ascii -encoding UTF-8 messages_cs.properties > messages_cs_escaped.properties

CHAPTER 16. INTERNATIONALIZATION, LOCALIZATION AND THEMES

221

Page 227: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

16.1.3. Other encoding settings

We need to make sure that the view displays your localized data and messages using the correctcharacter set and also any data submitted uses the correct encoding.

To set the display character encoding, you need to use the <f:view locale="cs_CZ"/> tag (herewe tell JSF to use the Czech locale). You may want to change the encoding of the xml document itselfif you want to embed localized strings in the xml. To do this alter the encoding attribute in xmldeclaration <?xml version="1.0" encoding="UTF-8"?> as required.

Also JSF/Facelets should submit any requests using the specified character encoding, but to makesure any requests that do not specify an encoding you can force the request encoding using a servletfilter. Configure this in components.xml:

16.2. LOCALES

Each user login session has an associated instance of java.util.Locale (available to theapplication as a component named locale). Under normal circumstances, you won't need to do anyspecial configuration to set the locale. Seam just delegates to JSF to determine the active locale:

If there is a locale associated with the HTTP request (the browser locale), and that locale is inthe list of supported locales from faces-config.xml, use that locale for the rest of thesession.

Otherwise, if a default locale was specified in the faces-config.xml, use that locale for therest of the session.

Otherwise, use the default locale of the server.

It is possible to set the locale manually via the Seam configuration properties org.jboss.seam.international.localeSelector.language, org.jboss.seam.international.localeSelector.country and org.jboss.seam.international.localeSelector.variant, but we can't think of any goodreason to ever do this.

It is, however, useful to allow the user to set the locale manually via the application user interface.Seam provides built-in functionality for overriding the locale determined by the algorithm above. Allyou have to do is add the following fragment to a form in your JSP or Facelets page:

Or, if you want a list of all supported locales from faces-config.xml, just use:

<web:character-encoding-filter encoding="UTF-8" override-client="true" url-pattern="*.seam" />

<h:selectOneMenu value="#{localeSelector.language}"> <f:selectItem itemLabel="English" itemValue="en"/> <f:selectItem itemLabel="Deutsch" itemValue="de"/> <f:selectItem itemLabel="Francais" itemValue="fr"/></h:selectOneMenu><h:commandButton action="#{localeSelector.select}" value="#{messages['ChangeLanguage']}"/>

Seam 2 Reference Guide

222

Page 228: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

When this use selects an item from the drop-down, and clicks the button, the Seam and JSF locales willbe overridden for the rest of the session.

16.3. LABELS

JSF supports internationalization of user interface labels and descriptive text via the use of <f:loadBundle />. You can use this approach in Seam applications. Alternatively, you can takeadvantage of the Seam messages component to display template labels with embedded ELexpressions.

16.3.1. Defining labels

Seam provides a java.util.ResourceBundle (available to the application as a org.jboss.seam.core.resourceBundle). You will need to make your internationalized labelsavailable via this special resource bundle. By default, the resource bundle used by Seam is named messages and so you will need to define your labels in files named messages.properties, messages_en.properties, messages_en_AU.properties, etc. These files usually belong in the WEB-INF/classes directory.

So, in messages_en.properties:

And in messages_en_AU.properties:

You can select a different name for the resource bundle by setting the Seam configuration propertynamed org.jboss.seam.core.resourceLoader.bundleNames. You can even specify a list ofresource bundle names to be searched (depth first) for messages.

If you want to define a message just for a particular page, you can specify it in a resource bundle withthe same name as the JSF view id, with the leading / and trailing file extension removed. So we couldput our message in welcome/hello_en.properties if we only needed to display the message on /welcome/hello.jsp.

You can even specify an explicit bundle name in pages.xml:

<h:selectOneMenu value="#{localeSelector.localeString}"> <f:selectItems value="#{localeSelector.supportedLocales}"/></h:selectOneMenu><h:commandButton action="#{localeSelector.select}" value="#{messages['ChangeLanguage']}"/>

Hello=Hello

Hello=G'day

<core:resource-loader> <core:bundle-names> <value>mycompany_messages</value> <value>standard_messages</value> </core:bundle-names></core:resource-loader>

<page view-id="/welcome/hello.jsp" bundle="HelloMessages"/>

CHAPTER 16. INTERNATIONALIZATION, LOCALIZATION AND THEMES

223

Page 229: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Then we could use messages defined in HelloMessages.properties on /welcome/hello.jsp.

16.3.2. Displaying labels

If you define your labels using the Seam resource bundle, you will be able to use them without having totype <f:loadBundle ... /> on every page. Instead, you can simply type:

or:

Even better, the messages themselves may contain EL expressions:

You can even use the messages in your code:

16.3.3. Faces messages

The facesMessages component is a super-convenient way to display success or failure messages tothe user. The functionality we just described also works for faces messages:

This will display Hello, Gavin King or G'day, Gavin, depending upon the user's locale.

16.4. TIMEZONES

There is also a session-scoped instance of java.util.Timezone, named org.jboss.seam.international.timezone, and a Seam component for changing the timezonenamed org.jboss.seam.international.timezoneSelector. By default, the timezone is thedefault timezone of the server. Unfortunately, the JSF specification says that all dates and timesshould be assumed to be UTC, and displayed as UTC, unless a timezone is explicitly specified using <f:convertDateTime>. This is an extremely inconvenient default behavior.

<h:outputText value="#{messages['Hello']}"/>

<h:outputText value="#{messages.Hello}"/>

Hello=Hello, #{user.firstName} #{user.lastName}

Hello=G'day, #{user.firstName}

@In private Map<String, String> messages;

@In("#{messages['Hello']}") private String helloMessage;

@Name("hello")@Statelesspublic class HelloBean implements Hello { @In FacesMessages facesMessages; public String sayIt() { facesMessages.addFromResourceBundle("Hello"); }}

Seam 2 Reference Guide

224

Page 230: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam overrides this behavior, and defaults all dates and times to the Seam timezone. In addition, Seamprovides the <s:convertDateTime> tag which always performs conversions in the Seam timezone.

16.5. THEMES

Seam applications are also very easily skinnable. The theme API is very similar to the localization API,but of course these two concerns are orthogonal, and some applications support both localization andthemes.

First, configure the set of supported themes:

NOTE

The first theme listed is the default theme.

Themes are defined in a properties file with the same name as the theme. For example, the defaulttheme is defined as a set of entries in default.properties. For example, default.propertiesmight define:

Usually the entries in a theme resource bundle will be paths to CSS styles or images and names offacelets templates (unlike localization resource bundles which are usually text).

Now we can use these entries in our JSP or facelets pages. For example, to theme the stylesheet in afacelets page:

Or, when the page definition resides in a subdirectory:

Most powerfully, facelets lets us theme the template used by a <ui:composition>:

<theme:theme-selector cookie-enabled="true"> <theme:available-themes> <value>default</value> <value>accessible</value> <value>printable</value> </theme:available-themes></theme:theme-selector>

css ../screen.csstemplate /template.xhtml

<link href="#{theme.css}" rel="stylesheet" type="text/css" />

<link href="#{facesContext.externalContext.requestContextPath}#{theme.css}" rel="stylesheet" type="text/css" />

<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" template="#{theme.template}">

CHAPTER 16. INTERNATIONALIZATION, LOCALIZATION AND THEMES

225

Page 231: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Just like the locale selector, there is a built-in theme selector to allow the user to freely switch themes:

16.6. PERSISTING LOCALE AND THEME PREFERENCES VIA COOKIES

The locale selector, theme selector and timezone selector all support persistence of locale and themepreference to a cookie. Simply set the cookie-enabled property in components.xml:

<h:selectOneMenu value="#{themeSelector.theme}"> <f:selectItems value="#{themeSelector.themes}"/></h:selectOneMenu><h:commandButton action="#{themeSelector.select}" value="Select Theme"/>

<theme:theme-selector cookie-enabled="true"> <theme:available-themes> <value>default</value> <value>accessible</value> <value>printable</value> </theme:available-themes></theme:theme-selector>

<international:locale-selector cookie-enabled="true"/>

Seam 2 Reference Guide

226

Page 232: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 17. SEAM TEXTCollaboration-oriented websites require a human-friendly markup language for easy entry offormatted text in forum posts, wiki pages, blogs, comments, etc. Seam provides the <s:formattedText/> control for display of formatted text that conforms to the Seam Text language.Seam Text is implemented using an ANTLR-based parser. You do not need to know anything aboutANTLR to use it, however.

17.1. BASIC FORMATTING

Here is a simple example:

If we display this using <s:formattedText/>, we will get the following HTML produced:

We can use a blank line to indicate a new paragraph, and + to indicate a heading:

(Note that a simple newline is ignored, you need an additional blank line to wrap text into a newparagraph.) This is the HTML that results:

Ordered lists are created using the # character. Unordered lists use the = character:

It's easy to make *emphasis*, |monospace|,~deleted text~, super^scripts^ or _underlines_.

<p>It's easy to make <i>emphasis</i>, <tt>monospace</tt><del>deleted text</del>, super<sup>scripts</sup> or <u>underlines</u>.</p>

+This is a big headingYou /must/ have some text following a heading! ++This is a smaller headingThis is the first paragraph. We can split it across multiple lines, but we must end it with a blank line.

This is the second paragraph.

<h1>This is a big heading</h1><p>You <i>must</i> have some text following a heading!</p> <h2>This is a smaller heading</h2><p>This is the first paragraph. We can split it across multiple lines, but we must end it with a blank line.</p>

<p>This is the second paragraph.</p>

CHAPTER 17. SEAM TEXT

227

Page 233: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Quoted sections should be surrounded in double quotes:

17.2. ENTERING CODE AND TEXT WITH SPECIAL CHARACTERS

An ordered list: #first item#second item#and even the /third/ item

An unordered list:

=an item=another item

<p>An ordered list:</p> <ol> <li>first item</li><li>second item</li><li>and even the <i>third</i> item</li></ol>

<p>An unordered list:</p>

<ul><li>an item</li><li>another item</li></ul>

The other guy said: "Nyeah nyeah-nee /nyeah/ nyeah!"

But what do you think he means by "nyeah-nee"?

<p>The other guy said:</p> <q>Nyeah nyeah-nee<i>nyeah</i> nyeah!</q>

<p>But what do you think he means by <q>nyeah-nee</q>?</p>

Seam 2 Reference Guide

228

Page 234: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Special characters such as *, | and #, along with HTML characters such as <, > and & may be escapedusing \:

And we can quote code blocks using backticks:

Sine inline monospace formatting always escapes (most monospace formatted text is in fact code ortags with many special characters), you can, for example, write:

without escaping any of the characters inside the monospace bars. The downside is that you can'tformat inline monospace text in any other way (italics, underscore, and so on).

17.3. LINKS

A link may be created using the following syntax:

Or, if you want to specify the text of the link:

You can write down equations like 2\*3\=6 and HTML tagslike \<body\> using the escape character: \\.

<p>You can write down equations like 2*3=6 and HTML tagslike <body> using the escape character: \.</p>

My code doesn't work:

`for (int i=0; i<100; i--){ doSomething();}`

Any ideas?

<p>My code doesn't work:</p>

<pre>for (int i=0; i<100; i--){ doSomething();}</pre>

<p>Any ideas?</p>

This is a |<tag attribute="value"/>| example.

Go to the Seam website at [=>http://jboss.com/products/seam].

Go to [the Seam website=>http://jboss.com/products/seam].

CHAPTER 17. SEAM TEXT

229

Page 235: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

For advanced users, it is even possible to customize the Seam Text parser to understand wikiword linkswritten using this syntax.

17.4. ENTERING HTML

Text may even include a certain limited subset of HTML (the subset is chosen to be safe from cross-site scripting attacks). This is useful for creating links:

And for creating tables:

There is also much more that can be achieved if you desire to delve.

You might want to link to <a href="http://jboss.com/products/seam">somethingcool</a>, or even include an image: <img src="/logo.jpg"/>

<table> <tr><td>First name:</td><td>Gavin</td></tr> <tr><td>Last name:</td><td>King</td></tr></table>

Seam 2 Reference Guide

230

Page 236: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 18. ITEXT PDF GENERATIONSeam now includes a component set for generating documents using iText. The primary focus ofSeam's iText document support is for the generation of PDF documents, but Seam also offers basicsupport for RTF document generation.

18.1. USING PDF SUPPORT

iText support is provided by jboss-seam-pdf.jar. This JAR contains the iText JSF controls, whichare used to construct views that can render to PDF, and the DocumentStore component, which servesthe rendered documents to the user. To include PDF support in your application, included jboss-seam-pdf.jar in your WEB-INF/lib directory along with the iText JAR file. There is no furtherconfiguration needed to use Seam's ciText supportfon.

The Seam iText module requires the use of Facelets as the view technology. Future versions of thelibrary may also support the use of JSP. Additionally, it requires the use of the seam-ui package.

The examples/itext project contains an example of the PDF support in action. It demonstratesproper deployment packaging, and it contains a number examples that demonstrate the key PDFgeneration features current supported.

18.1.1. Creating a document

<p:document> Description

Documents are generated by facelet XHTML filesusing tags in the http://jboss.com/products/seam/pdfnamespace. Documents should always have the document tag at the root of the document. The document tag prepares Seam to generate adocument into the DocumentStore and renders anHTML redirect to that stored content.

Attributes

type — The type of the document to beproduced. Valid values are PDF, RTF and HTML modes. Seam defaults to PDFgeneration, and many of the features onlywork correctly when generating PDFdocuments.

pageSize — The size of the page to begenerate. The most commonly used valueswould be LETTER and A4. A full list ofsupported pages sizes can be found in com.lowagie.text.PageSize class.Alternatively, pageSize can provide thewidth and height of the page directly. Thevalue "612 792", for example, is equivalentto the LETTER page size.

orientation — The orientation of thepage. Valid values are portrait and landscape. In landscape mode, theheight and width page size values arereversed.

CHAPTER 18. ITEXT PDF GENERATION

231

Page 237: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

margins — The left, right, top and bottommargin values.

marginMirroring — Indicates thatmargin settings should be reversed analternating pages.

disposition — When generating PDFs ina web browser, this determines the HTTP Content-Disposition of thedocument. Valid values are inline, whichindicates the document should be displayedin the browser window if possible, and attachment, which indicates that thedocument should be treated as a download.The default value is inline.

Metadata Attributes

title

subject

keywords

author

creator

Usage

18.1.2. Basic Text Elements

Useful documents will need to contain more than just text; however, the standard UI components aregeared towards HTML generation and are not useful for generating PDF content. Instead, Seamprovides a special UI components for generating suitable PDF content. Tags like <p:image> and <p:paragraph> are the basic foundations of simple documents. Tags like <p:font> provide styleinformation to all the content surrounding them.

<p:document xmlns:p="http://jboss.com/products/seam/pdf"> The document goes here. </p:document>

Seam 2 Reference Guide

232

Page 238: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:paragraph> Description

Most uses of text should be sectioned intoparagraphs so that text fragments can be flowed,formatted and styled in logical groups.

Attributes

firstLineIndent

extraParagraphSpace

leading

multipliedLeading

spacingBefore — The blank space to beinserted before the element.

spacingAfter — The blank space to beinserted after the element.

indentationLeft

indentationRight

keepTogether

Usage

<p:text> Description

The text tag allows text fragments to be producedfrom application data using normal JSF convertermechanisms. It is very similar to the outputTexttag used when rendering HTML documents.

Attributes

value — The value to be displayed. This willtypically be a value binding expression.

Usage

<p:paragraph alignment="justify"> This is a simple document. It isn't very fancy.</p:paragraph>

<p:paragraph> The item costs <p:text value="#{product.price}"> <f:convertNumber type="currency" currencySymbol="$"/> </p:text></p:paragraph>

CHAPTER 18. ITEXT PDF GENERATION

233

Page 239: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:html> Description

The html tag renders HTML content into the PDF.

Attributes

value — The text to be displayed.

Usage

<p:font> Description

The font tag defines the default font to be used forall text inside of it.

Attributes

name — The font name, for example: COURIER, HELVETICA, TIMES-ROMAN, SYMBOL or ZAPFDINGBATS.

size — The point size of the font.

style — The font styles. Any combinationof : NORMAL, BOLD, ITALIC, OBLIQUE, UNDERLINE, LINE-THROUGH

encoding — The character set encoding.

Usage

<p:html value="This is HTML with <b>some markup</b>." /><p:html> <h1>This is more complex HTML</h1> <ul> <li>one</li> <li>two</li> <li>three</li> </ul></p:html>

<p:html> <s:formattedText value="*This* is |Seam Text| as HTML. It's very^cool^." /></p:html>

<p:font name="courier" style="bold" size="24"> <p:paragraph>My Title</p:paragraph></p:font>

Seam 2 Reference Guide

234

Page 240: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:newPage> Description

p:newPage inserts a page break.

Usage

<p:image> Description

p:image inserts an image into the document.Images can be be loaded from the classpath or fromthe web application context using the valueattribute.

Resources can also be dynamically generated byapplication code. The imageData attribute canspecify a value binding expression whose value is a java.awt.Image object.

Attributes

value — A resource name or a methodexpression binding to an application-generated image.

rotation — The rotation of the image indegrees.

height — The height of the image.

width — The width of the image.

alignment— The alignment of the image.(see Section 18.1.7.2, “Alignment Values”for possible values)

alt — Alternative text representation forthe image.

indentationLeft

indentationRight

spacingBefore — The blank space to beinserted before the element.

spacingAfter — The blank space to beinserted after the element.

widthPercentage

initialRotation

dpi

scalePercent — The scaling factor (as apercentage) to use for the image. This canbe expressed as a single percentage valueor as two percentage values representingseparate x and y scaling percentages.

<p:newPage />

CHAPTER 18. ITEXT PDF GENERATION

235

Page 241: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

wrap

underlying

Usage

<p:anchor> Description

p:anchor defines clickable links from a document.It supports the following attributes:

Attributes

name — The name of an in-document anchordestination.

reference — The destination the linkrefers to. Links to other points in thedocument should begin with a "#". Forexample, "#link1" to refer to an anchorpostion with a name of link1. Links mayalso be a full URL to point to a resourceoutside of the document.

Usage

18.1.3. Headers and Footers

<p:image value="/jboss.jpg" />

<p:image value="#{images.chart}" />

<p:listItem><p:anchor reference="#reason1">Reason 1</p:anchor></p:listItem> ...<p:paragraph> <p:anchor name="reason1">It's the quickest way to get "rich"</p:anchor> ... </p:paragraph>

Seam 2 Reference Guide

236

Page 242: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:header>

<p:footer>

Description

The p:header and p:footer componentsprovide the ability to place header and footer texton each page of a generated document, with theexception of the first page. Header and footerdeclarations should appear near the top of adocument.

Attributes

alignment — The alignment of theheader/footer box section. (seeSection 18.1.7.2, “Alignment Values” foralignment values)

backgroundColor — The backgroundcolor of the header/footer box. (seeSection 18.1.7.1, “Color Values” for colorvalues)

borderColor — The border color of theheader/footer box. Individual border sidescan be set using borderColorLeft, borderColorRight, borderColorTop and borderColorBottom.(seeSection 18.1.7.1, “Color Values” for colorvalues)

borderWidth — The width of the border.Individual border sides can be specifiedusing borderWidthLeft, borderWidthRight, borderWidthTop and borderWidthBottom.

Usage

<p:facet name="header"> <p:font size="12"> <p:footer borderWidthTop="1" borderColorTop="blue" borderWidthBottom="0" alignment="center"> Why Seam? [<p:pageNumber />] </p:footer> </p:font></f:facet>

CHAPTER 18. ITEXT PDF GENERATION

237

Page 243: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:pageNumber> Description

The current page number can be placed inside of aheader or footer using the p:pageNumber tag. Thepage number tag can only be used in the context of aheader or footer and can only be used once.

Usage

18.1.4. Chapters and Sections

<p:footer borderWidthTop="1" borderColorTop="blue" borderWidthBottom="0" alignment="center"> Why Seam? [<p:pageNumber />]</p:footer>

Seam 2 Reference Guide

238

Page 244: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:chapter>

<p:section>

Description

If the generated document follows a book/articlestructure, the p:chapter and p:section tagscan be used to provide the necessary structure.Sections can only be used inside of chapters, butthey may be nested arbitrarily deep. Most PDFviewers provide easy navigation between chaptersand sections in a document.

Attributes

alignment — The alignment of theheader/footer box section. (seeSection 18.1.7.2, “Alignment Values” foralignment values)

number — The chapter number. Everychapter should be assigned a chapternumber.

numberDepth — The depth of numberingfor section. All sections are numberedrelative to their surroundingchapter/sections. The fourth section of ofthe first section of chapter three would besection 3.1.4, if displayed at the defaultnumber depth of three. To omit the chapternumber, a number depth of 2 should beused. In that case, the section numberwould be displayed as 1.4.

Usage

<p:document xmlns:p="http://jboss.com/products/seam/pdf" title="Hello">

<p:chapter number="1"> <p:title><p:paragraph>Hello</p:paragraph></p:title> <p:paragraph>Hello #{user.name}!</p:paragraph> </p:chapter>

<p:chapter number="2"> <p:title><p:paragraph>Goodbye</p:paragraph></p:title> <p:paragraph>Goodbye #{user.name}.</p:paragraph> </p:chapter>

</p:document>

CHAPTER 18. ITEXT PDF GENERATION

239

Page 245: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:header> Description

Any chapter or section can contain a p:title. Thetitle will be displayed next to the chapter/sectionnumber. The body of the title may contain raw textor may be a p:paragraph.

18.1.5. Lists

List structures can be displayed using the p:list and p:listItem tags. Lists may containarbitrarily-nested sublists. List items may not be used outside of a list. he following document uses the ui:repeat tag to to display a list of values retrieved from a Seam component.

<p:document xmlns:p="http://jboss.com/products/seam/pdf" xmlns:ui="http://java.sun.com/jsf/facelets" title="Hello"> <p:list style="numbered"> <ui:repeat value="#{documents}" var="doc"> <p:listItem>#{doc.name}</p:listItem> </ui:repeat> </p:list></p:document>

Seam 2 Reference Guide

240

Page 246: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:list> Attributes

style — The ordering/bulleting style oflist. One of: NUMBERED, LETTERED, GREEK, ROMAN, ZAPFDINGBATS, ZAPFDINGBATS_NUMBER. If no style isgiven, the list items are bulleted.

listSymbol — For bulleted lists, specifiesthe bullet symbol.

indent — The indentation level of the list.

lowerCase — For list styles using letters,indicates whether the letters should belower case.

charNumber — For ZAPFDINGBATS,indicates the character code of the bulletcharacter.

numberType — ForZAPFDINGBATS_NUMBER, indicates thenumbering style.

Usage

<p:list style="numbered"> <ui:repeat value="#{documents}" var="doc"> <p:listItem>#{doc.name}</p:listItem> </ui:repeat></p:list>

CHAPTER 18. ITEXT PDF GENERATION

241

Page 247: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:listItem> Description

p:listItem supports the following attributes:

Attributes

alignment — The alignment of theheader/footer box section. (seeSection 18.1.7.2, “Alignment Values” foralignment values)

alignment — The alignment of the listitem. (See Section 18.1.7.2, “AlignmentValues” for possible values)

indentationLeft — The leftindentation amount.

indentationRight — The rightindentation amount.

listSymbol — Overrides the default listsymbol for this list item.

Usage

18.1.6. Tables

Table structures can be created using the p:table and p:cell tags. Unlike many table structures,there is no explicit row declaration. If a table has 3 columns, then every 3 cells will automatically form arow. Header and footer rows can be declared, and the headers and footers will be repeated in the eventa table structure spans multiple pages.

<p:table> Description

p:table supports the following attributes.

Attributes

columns — The number of columns (cells)that make up a table row.

widths — The relative widths of eachcolumn. There should be one value for eachcolumn. For example: widths="2 1 1" wouldindicate that there are 3 columns and thefirst column should be twice the size of thesecond and third column.

headerRows — The initial number of rowswhich are considered to be headers orfooter rows and should be repeated if thetable spans multiple pages.

footerRows — The number of rows thatare considered to be footer rows. This valueis subtracted from the headerRows value.

...

Seam 2 Reference Guide

242

Page 248: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If document has 2 rows which make up theheader and one row that makes up thefooter, headerRows should be set to 3and footerRows should be set to 1

widthPercentage — The percentage ofthe page width that the table spans.

horizontalAlignment — Thehorizontal alignment of the table. (SeeSection 18.1.7.2, “Alignment Values” forpossible values)

skipFirstHeader

runDirection

lockedWidth

splitRows

spacingBefore — The blank space to beinserted before the element.

spacingAfter — The blank space to beinserted after the element.

extendLastRow

headersInEvent

splitLate

keepTogether

Usage

<p:cell> Description

p:cell supports the following attributes.

Attributes

colspan — Cells can span more than onecolumn by declaring a colspan greaterthan 1. Tables do not have the ability tospan across multiple rows.

<p:table columns="3" headerRows="1"> <p:cell>name</p:cell> <p:cell>owner</p:cell> <p:cell>size</p:cell> <ui:repeat value="#{documents}" var="doc"> <p:cell>#{doc.name}</p:cell> <p:cell>#{doc.user.name}</p:cell> <p:cell>#{doc.size}</p:cell> </ui:repeat></p:table>

CHAPTER 18. ITEXT PDF GENERATION

243

Page 249: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

horizontalAlignment — Thehorizontal alignment of the cell. (seeSection 18.1.7.2, “Alignment Values” forpossible values)

verticalAlignment — The verticalalignment of the cell. (see Section 18.1.7.2,“Alignment Values” for possible values)

padding — Padding on a given side canalso be specified using paddingLeft, paddingRight, paddingTop and paddingBottom.

useBorderPadding

leading

multipliedLeading

indent

verticalAlignment

extraParagraphSpace

fixedHeight

noWrap

minimumHeight

followingIndent

rightIndent

spaceCharRatio

runDirection

arabicOptions

useAscender

grayFill

rotation

Usage

18.1.7. Document Constants

This section documents some of the constants shared by attributes on multiple tags.

18.1.7.1. Color Values

<p:cell>...</p:cell>

Seam 2 Reference Guide

244

Page 250: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam documents do not yet support a full color specification. Currently, only named colors aresupported. They are: white, gray, lightgray, darkgray, black, red, pink, yellow, green, magenta, cyan and blue.

18.1.7.2. Alignment Values

Where alignment values are used, the Seam PDF supports the following horizontal alignment values: left, right, center, justify and justifyall. The vertical alignment values are top, middle, bottom, and baseline.

18.1.8. Configuring iText

Document generation works out of the box with no additional configuration needed. However, thereare a few points of configuration that are needed for more serious applications.

The default implementation serves PDF documents from a generic URL, /seam-doc.seam. Manybrowsers (and users) would prefer to see URLs that contain the actual PDF name like /myDocument.pdf. This capability requires some configuration. To serve PDF files, all *.pdf resourcesshould be mapped to the DocumentStoreServlet:

The use-extensions option on the document store component completes the functionality byinstructing the document store to generate URLs with the correct filename extension for thedocument type being generated.

Generated documents are stored in conversation scope and will expire when the conversation ends. Atthat point, references to the document will be invalid. To You can specify a default view to be shownwhen a document does not exist using the error-page property of the documentStore.

18.2. CHARTING

Charting support is also provided with jboss-seam-pdf.jar. Charts can be used in PDF documentsor can be used as images in an HTML page. Charting requires the JFreeChart library(jfreechart.jar and jcommon.jar) to be added to the WEB-INF/lib directory. Three types ofcharts are currently supported: pie charts, bar charts and line charts.

<servlet> <servlet-name>Document Store Servlet</servlet-name> <servlet-class>org.jboss.seam.pdf.DocumentStoreServlet</servlet-class></servlet>

<servlet-mapping> <servlet-name>Document Store Servlet</servlet-name> <url-pattern>*.pdf</url-pattern></servlet-mapping>

<components xmlns="http://jboss.com/products/seam/components" xmlns:pdf="http://jboss.com/products/seam/pdf"> <pdf:document-store use-extensions="true" /></components>

<pdf:document-store use-extensions="true" error-page="/pdfMissing.seam" />

CHAPTER 18. ITEXT PDF GENERATION

245

Page 251: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:barchart> Description

Displays a bar chart.

Attributes

borderVisible — Controls whether ornot a border is displayed around the entirechart.

borderPaint — The color of the border, ifvisible;

borderBackgroundPaint — Thedefault background color of the chart.

borderStroke —

domainAxisLabel — The text label forthe domain axis.

domainAxisPaint — The color of thedomain axis label.

domainGridlinesVisible— Controlswhether or not gridlines for the domain axisare shown on the chart.

domainGridlinePaint— The color ofthe domain gridlines, if visible.

domainGridlineStroke — The strokestyle of the domain gridlines, if visible.

height — The height of the chart.

width — The width of the chart.

is3D — A boolean value indicating that thechart should be rendered in 3D instead of2D.

legend — A boolean value indicatingwhether or not the chart should include alegend.

legendItemPaint— The default color ofthe text labels in the legend.

legendItemBackgoundPaint— Thebackground color for the legend, if differentfrom the chart background color.

orientation — The orientation of theplot, either vertical (the default) or horizontal.

plotBackgroundPaint— The color ofthe plot background.

plotBackgroundAlpha— The alpha(transparency) level of the plot background.It should be a number between 0

Seam 2 Reference Guide

246

Page 252: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

(completely transparent) and 1 (completelyopaque).

plotForegroundAlpha— The alpha(transparency) level of the plot. It should bea number between 0 (completelytransparent) and 1 (completely opaque).

plotOutlinePaint— The color of therange gridlines, if visible.

plotOutlineStroke — The stroke styleof the range gridlines, if visible.

rangeAxisLabel — The text label for therange axis.

rangeAxisPaint — The color of therange axis label.

rangeGridlinesVisible— Controlswhether or not gridlines for the range axisare shown on the chart.

rangeGridlinePaint— The color of therange gridlines, if visible.

rangeGridlineStroke — The strokestyle of the range gridlines, if visible.

title — The chart title text.

titlePaint— The color of the chart titletext.

titleBackgroundPaint— Thebackground color around the chart title.

width — The width of the chart.

Usage

<p:linechart> Description

<p:barchart title="Bar Chart" legend="true" width="500" height="500"> <p:series key="Last Year"> <p:data columnKey="Joe" value="100" /> <p:data columnKey="Bob" value="120" /> </p:series> <p:series key="This Year"> <p:data columnKey="Joe" value="125" /> <p:data columnKey="Bob" value="115" /> </p:series></p:barchart>

CHAPTER 18. ITEXT PDF GENERATION

247

Page 253: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Displays a line chart.

Attributes

borderVisible — Controls whether ornot a border is displayed around the entirechart.

borderPaint — The color of the border, ifvisible;

borderBackgroundPaint — Thedefault background color of the chart.

borderStroke —

domainAxisLabel — The text label forthe domain axis.

domainAxisPaint — The color of thedomain axis label.

domainGridlinesVisible— Controlswhether or not gridlines for the domain axisare shown on the chart.

domainGridlinePaint— The color ofthe domain gridlines, if visible.

domainGridlineStroke — The strokestyle of the domain gridlines, if visible.

height — The height of the chart.

width — The width of the chart.

is3D — A boolean value indicating that thechart should be rendered in 3D instead of2D.

legend — A boolean value indicatingwhether or not the chart should include alegend.

legendItemPaint— The default color ofthe text labels in the legend.

legendItemBackgoundPaint— Thebackground color for the legend, if differentfrom the chart background color.

orientation — The orientation of theplot, either vertical (the default) or horizontal.

plotBackgroundPaint— The color ofthe plot background.

plotBackgroundAlpha— The alpha(transparency) level of the plot background.It should be a number between 0(completely transparent) and 1 (completelyopaque).

Seam 2 Reference Guide

248

Page 254: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

plotForegroundAlpha— The alpha(transparency) level of the plot. It should bea number between 0 (completelytransparent) and 1 (completely opaque).

plotOutlinePaint— The color of therange gridlines, if visible.

plotOutlineStroke — The stroke styleof the range gridlines, if visible.

rangeAxisLabel — The text label for therange axis.

rangeAxisPaint — The color of therange axis label.

rangeGridlinesVisible— Controlswhether or not gridlines for the range axisare shown on the chart.

rangeGridlinePaint— The color of therange gridlines, if visible.

rangeGridlineStroke — The strokestyle of the range gridlines, if visible.

title — The chart title text.

titlePaint— The color of the chart titletext.

titleBackgroundPaint— Thebackground color around the chart title.

width — The width of the chart.

Usage

<p:piechart> Description

<p:linechart title="Line Chart" width="500" height="500"> <p:series key="Prices"> <p:data columnKey="2003" value="7.36" /> <p:data columnKey="2004" value="11.50" /> <p:data columnKey="2005" value="34.625" /> <p:data columnKey="2006" value="76.30" /> <p:data columnKey="2007" value="85.05" /> </p:series></p:linechart>

CHAPTER 18. ITEXT PDF GENERATION

249

Page 255: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Displays a pie chart.

Attributes

title— The chart title text.

label— The default label text for piesections.

legend— A boolean value indicatingwhether or not the chart should include alegend. Default value is true

is3D—A boolean value indicating that thechart should be rendered in 3D instead of2D.

labelLinkMargin— The link margin forlabels.

labelLinkPaint— The paint used forthe label linking lines.

labelLinkStroke— he stroke used forthe label linking lines.

labelLinksVisible— A flag thatcontrols whether or not the label links aredrawn.

labelOutlinePaint— The paint usedto draw the outline of the section labels.

labelOutlineStroke— The strokeused to draw the outline of the sectionlabels.

labelShadowPaint— The paint used todraw the shadow for the section labels.

labelPaint— The color used to draw thesection labels

labelGap— The gap between the labelsand the plot as a percentage of the plotwidth.

labelBackgroundPaint— The colorused to draw the background of the sectionlabels. If this is null, the background is notfilled.

startAngle— The starting angle of thefirst section.

circular— A boolean value indicatingthat the chart should be drawn as a circle. Iffalse, the chart is drawn as an ellipse. Thedefault is true.

direction— The direction the pie sectionare drawn. One of: clockwise or anticlockwise. The default is clockwise.

Seam 2 Reference Guide

250

Page 256: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

sectionOutlinePaint— The outlinepaint for all sections.

sectionOutlineStroke— The outlinestroke for all sections

sectionOutlinesVisible— Indicateswhether an outline is drawn for eachsection in the plot.

baseSectionOutlinePaint— Thebase section outline paint.

baseSectionPaint— The base sectionpaint.

baseSectionOutlineStroke— Thebase section outline stroke.

Usage

<p:piechart title="Pie Chart" circular="false" direction="anticlockwise" startAngle="30" labelGap="0.1" labelLinkPaint="red"> <p:series key="Prices"> <p:data key="2003" columnKey="2003" value="7.36" /> <p:data key="2004" columnKey="2004" value="11.50" /> <p:data key="2005" columnKey="2005" value="34.625" /> <p:data key="2006" columnKey="2006" value="76.30" /> <p:data key="2007" columnKey="2007" value="85.05" /> </p:series> </p:piechart>

CHAPTER 18. ITEXT PDF GENERATION

251

Page 257: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:series> Description

Category data can be broken down into series. Theseries tag is used to categorize a set of data with aseries and apply styling to the entire series.

Attributes

key — The series name.

seriesPaint — The color of each item inthe series

seriesOutlinePaint — The outlinecolor for each item in the series.

seriesOutlineStroke — The strokeused to draw each item in the series.

seriesVisible — A boolean indicating ifthe series should be displayed.

seriesVisibleInLegend — A booleanindiciating if the series should be listed inthe legend.

Usage

<p:series key="data1"> <ui:repeat value="#{data.pieData1}" var="item"> <p:data columnKey="#{item.name}" value="#{item.value}" /> </ui:repeat></p:series>

Seam 2 Reference Guide

252

Page 258: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:data> Description

The data tag describes each data point to bedisplayed in the graph.

Attributes

key — The name of the data item.

series — The series name, when notembedded inside a <p:series>.

value — The numeric data value.

explodedPercent — For pie charts,indicates how exploded a from the pie apiece is.

sectionOutlinePaint — For barcharts, the color of the section outline.

sectionOutlineStroke — For barcharts, the stroke type for the sectionoutline.

sectionPaint — For bar charts, the colorof the section.

Usage

<p:data key="foo" value="20" sectionPaint="#111111" explodedPercent=".2" /><p:data key="bar" value="30" sectionPaint="#333333" /><p:data key="baz" value="40" sectionPaint="#555555" sectionOutlineStroke="my-dot-style" />

CHAPTER 18. ITEXT PDF GENERATION

253

Page 259: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:color> Description

The color component declares a color or gradientthan can be referenced when drawing filled shapes.

Attributes

color — The color value. For gradientcolors, this the starting color.Section 18.1.7.1, “Color Values”

color2 — For gradient colors, this is thecolor that ends the gradient.

point — The co-ordinates where thegradient color begins.

point2 — The co-ordinates where thegradient color ends.

Usage

<p:color id="foo" color="#0ff00f"/><p:color id="bar" color="#ff00ff" color2="#00ff00" point="50 50" point2="300 300"/>

Seam 2 Reference Guide

254

Page 260: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:stroke> Description

Describes a stroke used to draw lines in a chart.

Attributes

width — The width of the stroke.

cap — The line cap type. Valid values are butt, round and square

join — The line join type. Valid values are miter, round and bevel

miterLimit — For miter joins, this valueis the limit of the size of the join.

dash — The dash value sets the dashpattern to be used to draw the line. Thespace separated integers indicate thelength of each alternating drawn andundrawn segments.

dashPhase — The dash phase indicatesthe offset into the dash pattern that the theline should be drawn with.

Usage

18.3. BAR CODES

Seam can use iText to generate barcodes in a wide variety of formats. These barcodes can beembedded in a PDF document or displayed as an image on a web page. Note that when used with HTMLimages, barcodes can not currently display barcode text in the barcode.

<p:stroke id="dot2" width="2" cap="round" join="bevel" dash="2 3" />

CHAPTER 18. ITEXT PDF GENERATION

255

Page 261: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<p:barCode> Description

Displays a barcode image.

Attributes

type — A barcode type supported by iText.Valid values include: EAN13, EAN8, UPCA, UPCE, SUPP2, SUPP5, POSTNET, PLANET,CODE128, CODE128_UCC, CODE128_RAW and CODABAR.

code— The value to be encoded by thebarcode.

xpos— For PDFs, the absolute y position ofthe barcode on the page.

ypos— For PDFs, the absolute y position ofthe barcode on the page.

rotDegrees — For PDFs, the rotationfactor of the barcode in degrees.

barHeight — The height of the bars in thebarCode

minBarWidth — The minimum bar width.

barMultiplier — The bar multiplier forwide bars or the distance between bars for POSTNET and PLANET code.

barColor — The color to draw the bars.

textColor — The color of any text on thebarcode.

textSize — The size of the barcode text,if any.

altText — The alt text for HTML imagelinks.

Usage

18.4. RENDERING SWING/AWT COMPONENTS

<p:barCode type="code128" barHeight="80" textSize="20" code="(10)45566(17)040301" codeType="code128_ucc" altText="My BarCode" />

Seam 2 Reference Guide

256

Page 262: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam now provides experimental support for rendering Swing components to into a PDF image. SomeSwing look and feels supports, notably ones that use native widgets, will not render correctly.

<p:swing> Description

Renders a Swing component into a PDF document.

Attributes

width — The width of the component to berendered.

height — ..The height of the component tobe rendered.

component — An expression whose valueis a Swing or AWT component.

Usage

18.5. FURTHER DOCUMENTATION

For further information on iText, see:

iText Home Page

iText in Action

<p:swing width="310" height="120" component="#{aButton}" />

CHAPTER 18. ITEXT PDF GENERATION

257

Page 263: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 19. EMAILSeam now includes optional components for creating templates and sending emails.

Email support is provided by jboss-seam-mail.jar. This JAR contains the mail JSF controls, whichare used to construct emails, and the mailSession manager component.

The examples/mail project contains an example of the email support in action. It demonstrates properpackaging, and it contains a number of examples that demonstrate the key features currentlysupported.

You can also test your mail project using Seam's integration testing environment. See Section 31.3.4,“Integration Testing Seam Mail”.

19.1. CREATING A MESSAGE

You do not need to learn a whole new template language to use Seam Mail — an email is just facelet.

The <m:message> tag wraps the whole message, and tells Seam to start rendering an email. Inside the<m:message> tag we use an <m:from> tag to set who the message is from, a <m:to> tag to specify asender (notice how we use EL as we would in a normal facelet), and a <m:subject> tag.

The <m:body> tag wraps the body of the email. You can use regular HTML tags inside the body as wellas JSF components.

So, now you have your email template, how do you go about sending it? Well, at the end of renderingthe m:message the mailSession is called to send the email, so all you have to do is ask Seam torender the view:

<m:message xmlns="http://www.w3.org/1999/xhtml" xmlns:m="http://jboss.com/products/seam/mail" xmlns:h="http://java.sun.com/jsf/html"> <m:from name="Peter" address="[email protected]" /> <m:to name="#{person.firstname} #{person.lastname}">#{person.address}</m:to> <m:subject>Try out Seam!</m:subject> <m:body> <p><h:outputText value="Dear #{person.firstname}" />,</p> <p>You can try out Seam by visiting <a href="http://labs.jboss.com/jbossseam">http://labs.jboss.com/jbossseam</a>.</p> <p>Regards,</p> <p>Pete</p> </m:body> </m:message>

@In(create=true)private Renderer renderer; public void send() { try {

Seam 2 Reference Guide

258

Page 264: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If, for example, you entered an invalid email address, then an exception would be thrown, which iscaught and then displayed to the user.

19.1.1. Attachments

Seam makes it easy to attach files to an email. It supports most of the standard java types used whenworking with files.

If you wanted to email the jboss-seam-mail.jar:

Seam will load the file from the classpath, and attach it to the email. By default it would be attached as jboss-seam-mail.jar; if you wanted it to have another name you would just add the fileNameattribute:

You could also attach a java.io.File and a java.net.URL:

Or a byte[] or a java.io.InputStream:

You will notice that for a byte[] and a java.io.InputStream you need to specify the MIME type ofthe attachment (as that information is not carried as part of the file).

You can also attach a Seam generated PDF, or any standard JSF view, just by wrapping a <m:attachment> around the normal tags you would use:

If you had a set of files you wanted to attach (for example a set of pictures loaded from a database) youcan just use a <ui:repeat>:

renderer.render("/simple.xhtml"); facesMessages.add("Email sent successfully"); } catch (Exception e) { facesMessages.add("Email sending failed: " + e.getMessage()); }}

<m:attachment value="/WEB-INF/lib/jboss-seam-mail.jar"/>

<m:attachment value="/WEB-INF/lib/jboss-seam-mail.jar" fileName="this-is-so-cool.jar"/>

<m:attachment value="#{numbers}"/>

<m:attachment value="#{person.photo}" contentType="image/png"/>

<m:attachment fileName="tiny.pdf"> <p:document> A very tiny PDF </p:document></m:attachment>

<ui:repeat value="#{people}" var="person"> <m:attachment value="#{person.photo}" contentType="image/jpeg" fileName="#{person.firstname}_#{person.lastname}.jpg"/>

CHAPTER 19. EMAIL

259

Page 265: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

And if you want to display an attached image inline:

You may be wondering what cid:#{...} does. Well, the IETF specified that by putting this as the srcfor your image, the attachments will be looked at when trying to locate the image (the Content-ID'smust match) — magic!

You must declare the attachment before trying to access the status object.

19.1.2. HTML/Text alternative part

Whilst most mail readers nowadays support HTML, some do not, so you can add a plain text alternativeto your email body:

19.1.3. Multiple recipients

Often you will want to send an email to a group of recipients (for example your users). All of therecipient mail tags can be placed inside a <ui:repeat>:

19.1.4. Multiple messages

Sometimes, however, you need to send a slightly different message to each recipient (for example, apassword reset). The best way to do this is to place the whole message inside a <ui:repeat>:

</ui:repeat>

<m:attachment value="#{person.photo}" contentType="image/jpeg" fileName="#{person.firstname}_#{person.lastname}.jpg" status="personPhoto" disposition="inline" /><img src="cid:#{personPhoto.contentId}" />

<m:body> <f:facet name="alternative">Sorry, your email reader can't show our fancy email, please go to http://labs.jboss.com/jbossseam to explore Seam.</f:facet></m:body>

<ui:repeat value="#{allUsers} var="user"> <m:to name="#{user.firstname} #{user.lastname}" address="#{user.emailAddress}" /></ui:repeat>

<ui:repeat value="#{people}" var="p"> <m:message> <m:from name="#{person.firstname} #{person.lastname}">#{person.address}</m:from> <m:to name="#{p.firstname}">#{p.address}</m:to> ... </m:message></ui:repeat>

Seam 2 Reference Guide

260

Page 266: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

19.1.5. Templates

The mail template example shows that facelets templates work with the Seam mail tags without effort.

Our template.xhtml contains:

Our templating.xhtml contains:

You can also use facelets source tags in your email, but you must place them in a jar in WEB-INF/lib -referencing the .taglib.xml from web.xml is not reliable when using Seam Mail (if you send yourmail asynchronously Seam Mail doesn't have access to the full JSF or Servlet context, and so does notknow about web.xml configuration parameters).

If you do need more configure Facelets or JSF when sending mail, you will need to override theRenderer component and do the configuration programmatically; this should only be configured byadvanced users

19.1.6. Internationalization

Seam supports sending internationalized messages. By default, the encoding provided by JSF is used,but this can be overridden on the template:

The body, subject and recipient (and from) name will be encoded. You will need to make sure faceletsuses the correct charset for parsing your pages by setting encoding of the template:

19.1.7. Other Headers

<m:message> <m:from name="Seam" address="[email protected]" /> <m:to name="#{person.firstname} #{person.lastname}">#{person.address}</m:to> <m:subject>#{subject}</m:subject> <m:body> <html> <body> <ui:insert name="body">This is the default body, specified by the template.</ui:insert> </body> </html> </m:body></m:message>

<ui:param name="subject" value="Templating with Seam Mail"/><ui:define name="body"> <p>This example demonstrates that you can easily use <i>facelets templating</i> in email!</p></ui:define>

<m:message charset="UTF-8"> ...</m:message>

<?xml version="1.0" encoding="UTF-8"?>

CHAPTER 19. EMAIL

261

Page 267: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Sometimes you will want to add other headers to your email. Seam provides support for some (seeSection 19.4, “Tags”). For example, we can set the importance of the email, and ask for a read receipt:

Otherwise you can add any header to the message using the <m:header> tag:

19.2. RECEIVING EMAILS

If you are using EJB then you can use a MDB (Message Driven Bean) to receive email. JBoss come alsowith a JCA adaptor — mail-ra.rar.

NOTE

Distributed mail-ra.rar in Seam is marked as technology preview, therefore standardproduction support is not guaranteed.

For testing purposes, you can use the mail-ra.rar distributed with Seam (it is in the extras/directory in the Seam bundle).

IMPORTANT

Back up the mail-ra.rar folder in the /deploy directory before replacing with the Seamversion.

To test the functionality, place the Seam mail-ra.rar folder in $JBOSS_HOME/server/$PROFILE/deploy.

You can configure the MDB using the following configuration:

<m:message xmlns:m="http://jboss.com/products/seam/mail" importance="low" requestReadReceipt="true"/>

<m:header name="X-Sent-From" value="JBoss Seam"/>

@MessageDriven(activationConfig={ @ActivationConfigProperty(propertyName="mailServer", propertyValue="localhost"), @ActivationConfigProperty(propertyName="mailFolder", propertyValue="INBOX"), @ActivationConfigProperty(propertyName="storeProtocol", propertyValue="pop3"), @ActivationConfigProperty(propertyName="userName", propertyValue="seam"), @ActivationConfigProperty(propertyName="password", propertyValue="seam")})@ResourceAdapter("mail-ra.rar")@Name("mailListener")public class MailListenerMDB implements MailListener {

@In(create=true) private OrderProcessor orderProcessor;

Seam 2 Reference Guide

262

Page 268: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Each message received will cause onMessage(Message message) to be called. Most Seamannotations will work inside a MDB but you must not access the persistence context.

You can find more information about mail-ra.rar athttp://community.jboss.org/wiki/InboundJavaMail.

19.3. CONFIGURATION

To include Email support in your application, include jboss-seam-mail.jar in your WEB-INF/libdirectory. If you are using JBoss Enterprise Application Platform there is no further configurationneeded to use Seam's email support. Otherwise you need to make sure you have the JavaMail API, animplementation of the JavaMail API present (the API and impl used in the JBoss Enterprise ApplicationPlatform are distributed with Seam as lib/mail.jar), and a copy of the Java Activation Framework(distributed with Seam as lib/activation.jar.

The Seam Email module requires the use of Facelets as the view technology. Future versions of thelibrary may also support the use of JSP. Additionally, it requires the use of the seam-ui package.

The mailSession component uses JavaMail to talk to a correctly configured SMTP server.

19.3.1. mailSession

A JavaMail Session may be available via a JNDI lookup if you are working in an JEE environment oryou can use a Seam configured Session.

The mailSession component's properties are described in more detail in Section 28.8, “Mail-relatedcomponents”.

19.3.1.1. JNDI lookup in JBoss AS

The JBoss Enterprise Application Platform deploy/mail-service.xml file configures a JavaMailsession binding into JNDI. The default service configuration will need altering for your network.http://wiki.jboss.org/wiki/Wiki.jsp?page=JavaMail describes the service in more detail.

Here we tell Seam to get the mail session bound to java:/Mail from JNDI.

19.3.1.2. Seam configured Session

public void onMessage(Message message) { // Process the message orderProcessor.process(message.getSubject()); } }

<components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core" xmlns:mail="http://jboss.com/products/seam/mail"> <mail:mail-session session-jndi-name="java:/Mail"/> </components>

CHAPTER 19. EMAIL

263

Page 269: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

A mail session can be configured via components.xml. Here we tell Seam to use smtp.example.comas the smtp server:

19.4. TAGS

Emails are generated using tags in the http://jboss.com/products/seam/mail namespace.Documents should always have the message tag at the root of the message. The message tagprepares Seam to generate an email.

The standard templating tags of facelets can be used as normal. Inside the body you can use any JSFtag; if it requires access to external resources (stylesheets, javascript) then be sure to set the urlBase.

<m:message>

Root tag of a mail message

importance — low, normal or high. By default normal, this sets the importance of the mailmessage.

precedence — sets the precedence of the message (e.g. bulk).

requestReadReceipt — by default false, if set, a read receipt request will be will be added,with the read receipt being sent to the From: address.

urlBase — If set, the value is prepended to the requestContextPath allowing you to usecomponents such as <h:graphicImage> in your emails.

<m:from>

Sets the From: address for the email. You can only have one of these per email.

name — the name the email should come from.

address — the email address the email should come from.

<m:replyTo>

Sets the Reply-to: address for the email. You can only have one of these per email.

address — the email address the email should come from.

<m:to>

Add a recipient to the email. Use multiple <m:to> tags for multiple recipients. This tag can be safelyplaced inside a repeat tag such as <ui:repeat>.

name — the name of the recipient.

<components xmlns="http://jboss.com/products/seam/components" xmlns:core="http://jboss.com/products/seam/core" xmlns:mail="http://jboss.com/products/seam/mail"> <mail:mail-session host="smtp.example.com"/> </components>

Seam 2 Reference Guide

264

Page 270: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

address — the email address of the recipient.

<m:cc>

Add a cc recipient to the email. Use multiple <m:cc> tags for multiple ccs. This tag can be safelyplaced inside a iterator tag such as <ui:repeat>.

name — the name of the recipient.

address — the email address of the recipient.

<m:bcc>

Add a bcc recipient to the email. Use multiple <m:bcc> tags for multiple bccs. This tag can be safelyplaced inside a repeat tag such as <ui:repeat>.

name — the name of the recipient.

address — the email address of the recipient.

<m:header>

Add a header to the email (for example, X-Sent-From: JBoss Seam)

name — The name of the header to add (for example, X-Sent-From).

value — The value of the header to add (for example, JBoss Seam).

<m:attachment>

Add an attachment to the email.

value — The file to attach:

String — A String is interpreted as a path to file within the classpath

java.io.File — An EL expression can reference a File object

java.net.URL — An EL expression can reference a URL object

java.io.InputStream — An EL expression can reference an InputStream. In thiscase both a fileName and a contentType must be specified.

byte[] — An EL expression can reference an byte[]. In this case both a fileNameand a contentType must be specified.

If the value attribute is omitted:

If this tag contains a <p:document> tag, the document described will be generatedand attached to the email. A fileName should be specified.

If this tag contains other JSF tags a HTML document will be generated from them andattached to the email. A fileName should be specified.

fileName — Specify the file name to use for the attached file.

contentType — Specify the MIME type of the attached file

CHAPTER 19. EMAIL

265

Page 271: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<m:subject>

Sets the subject for the email.

<m:body>

Sets the body for the email. Supports an alternative facet which, if an HTML email is generatedcan contain alternative text for a mail reader which doesn't support html.

type — If set to plain then a plain text email will be generated otherwise an HTML email isgenerated.

Seam 2 Reference Guide

266

Page 272: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 20. ASYNCHRONOUS AND MESSAGINGSeam makes it very easy to perform work asynchronously from a web request. When most people thinkof asynchronous in Java EE, they think of using JMS. This is certainly one way to approach the problemin Seam, and is the right way when you have strict and well-defined quality of service requirements.Seam makes it easy to send and receive JMS messages using Seam components.

But for many usecases, JMS is overkill. Seam layers a simple asynchronous method and event facilityover your choice of dispatchers:

java.util.concurrent.ScheduledThreadPoolExecutor (by default)

the EJB timer service (for EJB 3.0 environments)

Quartz

20.1. ASYNCHRONOUSLY

Asynchronous events and method calls have the same quality of service expectations as theunderlying dispatcher mechanism. The default dispatcher, based upon a ScheduledThreadPoolExecutor performs efficiently but provides no support for persistentasynchronous tasks, and hence no guarantee that a task will ever actually be executed. If you areworking in an environment that supports EJB 3.0, and add the following line to components.xml:

then your asynchronous tasks will be processed by the container's EJB timer service. If you're notfamiliar with the Timer service, don't worry, you don't need to interact with it directly if you want touse asynchronous methods in Seam. The important thing to know is that any good EJB 3.0implementation will have the option of using persistent timers, which gives some guarantee that thetasks will eventually be processed.

Another alternative is to use the open source Quartz library to manage asynchronous method. Youneed to bundle the Quartz library JAR (found in the lib directory) in your EAR and declare it as a Javamodule in application.xml. In addition, you need to add the following line to components.xml toinstall the Quartz dispatcher.

The Seam API for the default ScheduledThreadPoolExecutor, the EJB3 Timer, and the Quartz Scheduler are largely the same. They can just "plug and play" by adding a line to components.xml.

20.1.1. Asynchronous methods

In simplest form, an asynchronous call just lets a method call be processed asynchronously (in adifferent thread) from the caller. We usually use an asynchronous call when we want to return animmediate response to the client, and let some expensive work be processed in the background. Thispattern works very well in applications which use AJAX, where the client can automatically poll theserver for the result of the work.

For EJB components, we annotate the implementation of the bean to specify that a method isprocessed asynchronously. For JavaBean components we annotate the component implementationclass.

<async:timer-service-dispatcher/>

<async:quartz-dispatcher/>

CHAPTER 20. ASYNCHRONOUS AND MESSAGING

267

Page 273: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The use of asynchronous is transparent to the bean class:

And also transparent to the client:

The asynchronous method is processed in a completely new event context and does not have accessto the session or conversation context state of the caller. However, the business process context ispropagated.

Asynchronous method calls may be scheduled for later execution using the @Duration, @Expiration and @IntervalDuration annotations.

@Stateless@Name("paymentHandler")public class PaymentHandlerBean implements PaymentHandler{ @Asynchronous public void processPayment(Payment payment) { //code to go here }}

@Stateful@Name("paymentAction")public class CreatePaymentAction{ @In(create=true) PaymentHandler paymentHandler; @In Bill bill; public String pay() { paymentHandler.processPayment( new Payment(bill) ); return "success"; }}

@Localpublic interface PaymentHandler{ @Asynchronous public void processScheduledPayment(Payment payment, @Expiration Date date);

@Asynchronous public void processRecurringPayment(Payment payment, @Expiration Date date, @IntervalDuration Long interval)'}

@Stateful@Name("paymentAction")public class CreatePaymentAction{ @In(create=true) PaymentHandler paymentHandler;

Seam 2 Reference Guide

268

Page 274: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Both client and server may access the Timer object associated with the invocation. The Timer objectshown below is the EJB3 timer when you use the EJB3 dispatcher. For the default ScheduledThreadPoolExecutor, the returned object is Future from the JDK. For the Quartzdispatcher, it returns QuartzTriggerHandle, which we will discuss in the next section.

@In Bill bill; public String schedulePayment() { paymentHandler.processScheduledPayment( new Payment(bill), bill.getDueDate() ); return "success"; }

public String scheduleRecurringPayment() { paymentHandler.processRecurringPayment( new Payment(bill), bill.getDueDate(), ONE_MONTH ); return "success"; }}

@Localpublic interface PaymentHandler{ @Asynchronous public Timer processScheduledPayment(Payment payment, @Expiration Date date);}

@Stateless@Name("paymentHandler")public class PaymentHandlerBean implements PaymentHandler{ @In Timer timer; public Timer processScheduledPayment(Payment payment, @Expiration Date date) { //do some work! return timer; //note that return value is completely ignored }

}

@Stateful@Name("paymentAction")public class CreatePaymentAction{ @In(create=true) PaymentHandler paymentHandler; @In Bill bill; public String schedulePayment()

CHAPTER 20. ASYNCHRONOUS AND MESSAGING

269

Page 275: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Asynchronous methods cannot return any other value to the caller.

20.1.2. Asynchronous methods with the Quartz Dispatcher

The Quartz dispatcher (see earlier on how to install it) allows you to use the @Asynchronous, @Duration, @Expiration, and @IntervalDuration annotations as above. But it has somepowerful additional features. The Quartz dispatcher supports three new annotations.

The @FinalExpiration annotation specifies an end date for the recurring task.

The method returns the QuartzTriggerHandle object, which you can use later to stop, pause, andresume the scheduler. The QuartzTriggerHandle object is serializable, so you can save it into thedatabase if you need to keep it around for extended period of time.

{ Timer timer = paymentHandler.processScheduledPayment( new Payment(bill), bill.getDueDate() ); return "success"; }}

// Defines the method in the "processor" component @Asynchronous public QuartzTriggerHandle schedulePayment(@Expiration Date when, @IntervalDuration Long interval, @FinalExpiration Date endDate, Payment payment) { // do the repeating or long running task until endDate } ... ... // Schedule the task in the business logic processing code // Starts now, repeats every hour, and ends on May 10th, 2010 Calendar cal = Calendar.getInstance (); cal.set (2010, Calendar.MAY, 10); processor.schedulePayment(new Date(), 60*60*1000, cal.getTime(), payment);

QuartzTriggerHandle handle = processor.schedulePayment(payment.getPaymentDate(), payment.getPaymentCron(), payment); payment.setQuartzTriggerHandle( handle ); // Save payment to DB // later ... // Retrieve payment from DB // Cancel the remaining scheduled tasks payment.getQuartzTriggerHandle().cancel();

Seam 2 Reference Guide

270

Page 276: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The @IntervalCron annotation supports Unix cron job syntax for task scheduling. For instance, thefollowing asynchronous method runs at 2:10pm and at 2:44pm every Wednesday in the month ofMarch.

The @IntervalBusinessDay annotation supports invocation on the nth Business Day scenario. Forinstance, the following asynchronous method runs at 14:00 on the 2nd business day of each month. Bydefault, it excludes all weekends and US federal holidays until 2010 from the business days.

The NthBusinessDay object contains the configuration of the invocation trigger. You can specifymore holidays (for example, company holidays, non-US holidays etc.) via the additionalHolidaysproperty.

// Define the method @Asynchronous public QuartzTriggerHandle schedulePayment(@Expiration Date when, @IntervalCron String cron, Payment payment) { // do the repeating or long running task } ... ... // Schedule the task in the business logic processing code QuartzTriggerHandle handle = processor.schedulePayment(new Date(), "0 10,44 14 ? 3 WED", payment);

// Define the method @Asynchronous public QuartzTriggerHandle schedulePayment(@Expiration Date when, @IntervalBusinessDay NthBusinessDay nth, Payment payment) { // do the repeating or long running task } ... ... // Schedule the task in the business logic processing code QuartzTriggerHandle handle = processor.schedulePayment(new Date(), new NthBusinessDay(2, "14:00", WEEKLY), payment);

public class NthBusinessDay implements Serializable{ int n; String fireAtTime; List <Date> additionalHolidays; BusinessDayIntervalType interval; boolean excludeWeekends; boolean excludeUsFederalHolidays;

public enum BusinessDayIntervalType { WEEKLY, MONTHLY, YEARLY }

CHAPTER 20. ASYNCHRONOUS AND MESSAGING

271

Page 277: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The @IntervalDuration, @IntervalCron, and @IntervalNthBusinessDay annotations aremutually exclusive. If they are used in the same method, a RuntimeException will be thrown.

20.1.3. Asynchronous events

Component-driven events may also be asynchronous. To raise an event for asynchronous processing,simply call the raiseAsynchronousEvent() method of the Events class. To schedule a timedevent, call the raiseTimedEvent() method, passing a schedule object (for the default dispatcher ortimer service dispatcher, use TimerSchedule). Components may observe asynchronous events in theusual way, but remember that only the business process context is propagated to the asynchronousthread.

20.2. MESSAGING IN SEAM

Seam makes it easy to send and receive JMS messages to and from Seam components.

20.2.1. Configuration

To configure Seam's infrastructure for sending JMS messages, you need to tell Seam about any topicsand queues you want to send messages to, and also tell Seam where to find the QueueConnectionFactory and/or TopicConnectionFactory.

Seam defaults to using UIL2ConnectionFactory which is the usual connection factory for use withJBossMQ. If you are using some other JMS provider, you need to set one or both of queueConnection.queueConnectionFactoryJndiName and topicConnection.topicConnectionFactoryJndiName in seam.properties, web.xml or components.xml.

You also need to list topics and queues in components.xml to install Seam managed TopicPublishers and QueueSenders:

20.2.2. Sending messages

public NthBusinessDay () { n = 1; fireAtTime = "12:00"; additionalHolidays = new ArrayList <Date> (); interval = BusinessDayIntervalType.WEEKLY; excludeWeekends = true; excludeUsFederalHolidays = true; } ... ...}

<jms:managed-topic-publisher name="stockTickerPublisher" auto-create="true" topic-jndi-name="topic/stockTickerTopic"/>

<jms:managed-queue-sender name="paymentQueueSender" auto-create="true" queue-jndi-name="queue/paymentQueue"/>

Seam 2 Reference Guide

272

Page 278: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Now, you can inject a JMS TopicPublisher and TopicSession into any component:

Or, for working with a queue:

20.2.3. Receiving messages using a message-driven bean

You can process messages using any EJB3 message driven bean. Message-driven beans may even beSeam components, in which case it is possible to inject other event and application scoped Seamcomponents.

20.2.4. Receiving messages in the client

Seam Remoting lets you subscribe to a JMS topic from client-side JavaScript. This is described inChapter 23, Remoting.

@In private TopicPublisher stockTickerPublisher; @In private TopicSession topicSession;

public void publish(StockPrice price) { try { stockTickerPublisher.publish( topicSession.createObjectMessage(price) ); } catch (Exception ex) { throw new RuntimeException(ex); } }

@Inprivate QueueSender paymentQueueSender; @Inprivate QueueSession queueSession;

public void publish(Payment payment) { try { paymentQueueSender.send( queueSession.createObjectMessage(payment) ); } catch (Exception ex) { throw new RuntimeException(ex); } }

CHAPTER 20. ASYNCHRONOUS AND MESSAGING

273

Page 279: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 21. CACHINGThe database is the primary bottleneck in almost all enterprise applications, and the least-scalable tierof the runtime environment, so anything we can do to reduce the number of times the database isaccessed can dramatically improve application performance.

A well-designed Seam application will feature a rich, multi-layered caching strategy that impacts everylayer of the application, including:

The database has its own cache. This is particularly important, but cannot scale like a cache inthe application tier.

Your ORM solution (Hibernate, or some other JPA implementation) has a second-level cache ofdata from the database. This is a very powerful capability, but is often misused. In a clusteredenvironment, keeping the data in the cache transactionally consistent across the wholecluster, and with the database, is quite expensive. It makes most sense for data which is sharedbetween many users, and is updated rarely. In traditional stateless architectures, people oftentry to use the second-level cache for conversational state. This is always bad, and is especiallywrong in Seam.

The Seam conversation context is a cache of conversational state. Components you put intothe conversation context can hold and cache state relating to the current user interaction.

In particular, the Seam-managed persistence context (or an extended EJB container-managedpersistence context associated with a conversation-scoped stateful session bean) acts as acache of data that has been read in the current conversation. This cache tends to have a prettyhigh hitrate. Seam optimizes the replication of Seam-managed persistence contexts in aclustered environment, and there is no requirement for transactional consistency with thedatabase (optimistic locking is sufficient) so you do not need to worry too much about theperformance implications of this cache, unless you read thousands of objects into a singlepersistence context.

The application can cache non-transactional state in the Seam application context. State keptin the application context is of course not visible to other nodes in the cluster.

The application can cache transactional state using the Seam pojoCache component, whichintegrates JBossCache into the Seam environment. This state will be visible to other nodes ifyou run JBoss cache in a clustered mode.

Finally, Seam lets you cache rendered fragments of a JSF page. Unlike the ORM second-levelcache, this cache is not automatically invalidated when data changes, so you need to writeapplication code to perform explicit invalidation, or set appropriate expiration policies.

For more information about the second-level cache, you will need to refer to the documentation ofyour ORM solution, since this is an extremely complex topic. In this section we will discuss the use ofJBossCache directly, via the pojoCache component, or as the page fragment cache, via the <s:cache> control.

21.1. USING JBOSSCACHE IN SEAM

The built-in pojoCache component manages an instance of org.jboss.cache.aop.PojoCache.You can safely put any immutable Java object in the cache, and it will be replicated across the cluster(assuming that replication is enabled). If you want to keep mutable objects in the cache, you will needto run the JBoss Cache bytecode preprocessor to ensure that changes to the objects will beautomatically detected and replicated.

Seam 2 Reference Guide

274

Page 280: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

To use pojoCache, all you need to do is put the JBossCache jars in the classpath, and provide aresource named treecache.xml with an appropriate cache configuration. JBoss Cache has manyscary and confusing configuration settings, so we won't discuss them here. Please refer to the JBossCache documentation for more information.

You can find a sample treecache.xml in examples/blog/resources/treecache.xml.

For an EAR deployment of Seam, we recommend that the JBoss Cache jars and configuration godirectly into the EAR. Make sure you place both jboss-cache.jar and jgroups.jar in your EAR'slib folder.

Now you can inject the cache into any Seam component:

If you want to have multiple JBoss Cache configurations in your application, use components.xml:

21.2. PAGE FRAGMENT CACHING

The most interesting use of JBoss Cache is the <s:cache> tag, Seam's solution to the problem of pagefragment caching in JSF. <s:cache> uses pojoCache internally, so you need to follow the steps listedabove before you can use it.

<s:cache> is used for caching some rendered content which changes rarely. For example, thewelcome page of our blog displays the recent blog entries:

@Name("chatroom")public class Chatroom { @In PojoCache pojoCache; public void join(String username) { try { Set<String> userList = (Set<String>) pojoCache.get("chatroom", "userList"); if (userList==null) { userList = new HashSet<String>(); pojoCache.put("chatroom", "userList", userList); } userList.put(username); } catch (CacheException ce) { throw new RuntimeException(ce); } }}

<core:pojo-cache name="myCache" cfg-resource-name="myown/cache.xml"/>

<s:cache key="recentEntries-#{blog.id}" region="welcomePageFragments"> <h:dataTable value="#{blog.recentEntries}" var="blogEntry"> <h:column> <h3>#{blogEntry.title}</h3> <div>

CHAPTER 21. CACHING

275

Page 281: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The key will let you have multiple cached versions of each page fragment. In this case, there is onecached version per blog. The region determines the JBossCache node that all version will be storedin. Different nodes may have different expiry policies (setup during the previous steps).

The issue with the <s:cache> tag is that it is unable to recognize when the underlying data changes(for example, when the blogger posts a new entry). So you need to evict the cached fragment manually:

Alternatively, if it is not critical that changes are immediately visible to the user, you could set a shortexpiry time on the JbossCache node.

<s:formattedText value="#{blogEntry.body}"/> </div> </h:column> </h:dataTable></s:cache>

public void post() { ... entityManager.persist(blogEntry); pojoCache.remove("welcomePageFragments", "recentEntries-" + blog.getId() );}

Seam 2 Reference Guide

276

Page 282: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 22. WEB SERVICESSeam integrates with JBossWS to allow standard JEE web services to take full advantage of Seam'scontextual framework, including support for conversational web services. This chapter walks throughthe steps required to allow web services to run within a Seam environment.

22.1. CONFIGURATION AND PACKAGING

To allow Seam to intercept web service requests so that the necessary Seam contexts can be createdfor the request, a special SOAP handler must be configured; org.jboss.seam.webservice.SOAPRequestHandler is a SOAPHandler implementation thatdoes the work of managing Seam's lifecycle during the scope of a web service request.

A special configuration file, standard-jaxws-endpoint-config.xml should be placed into the META-INF directory of the jar file that contains the web service classes. This file contains thefollowing SOAP handler configuration:

22.2. CONVERSATIONAL WEB SERVICES

So how are conversations propagated between web service requests? Seam uses a SOAP headerelement present in both the SOAP request and response messages to carry the conversation ID fromthe consumer to the service, and back again. Here is an example of a web service request that containsa conversation ID:

<jaxws-config xmlns="urn:jboss:jaxws-config:2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="urn:jboss:jaxws-config:2.0 jaxws-config_2_0.xsd"> <endpoint-config> <config-name>Seam WebService Endpoint</config-name> <pre-handler-chains> <javaee:handler-chain> <javaee:protocol-bindings>##SOAP11_HTTP</javaee:protocol-bindings> <javaee:handler> <javaee:handler-name>SOAP Request Handler</javaee:handler-name> <javaee:handler-class>org.jboss.seam.webservice.SOAPRequestHandler</javaee:handler-class> </javaee:handler> </javaee:handler-chain> </pre-handler-chains> </endpoint-config></jaxws-config>

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:seam="http://seambay.example.seam.jboss.org/"> <soapenv:Header> <seam:conversationId xmlns:seam='http://www.jboss.org/seam/webservice'>2</seam:conversationId> </soapenv:Header> <soapenv:Body>

CHAPTER 22. WEB SERVICES

277

Page 283: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

As you can see in the above SOAP message, there is a conversationId element within the SOAPheader that contains the conversation ID for the request, in this case 2. Unfortunately, because webservices may be consumed by a variety of web service clients written in a variety of languages, it is upto the developer to implement conversation ID propagation between individual web services that areintended to be used within the scope of a single conversation.

An important thing to note is that the conversationId header element must be qualified with anamespace of http://www.jboss.org/seam/webservice, otherwise Seam will not be able to readthe conversation ID from the request. Here's an example of a response to the above request message:

As you can see, the response message contains the same conversationId element as the request.

22.2.1. A Recommended Strategy

As web services must be implemented as either a stateless session bean or POJO, it is recommendedthat for conversational web services, the web service acts as a facade to a conversational Seamcomponent.

If the web service is written as a stateless session bean, then it is also possible to make it a Seamcomponent by giving it a @Name. Doing this allows Seam's bijection (and other) features to be used inthe web service class itself.

22.3. AN EXAMPLE WEB SERVICE

<seam:confirmAuction/> </soapenv:Body></soapenv:Envelope>

<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'> <env:Header> <seam:conversationId xmlns:seam='http://www.jboss.org/seam/webservice'>2</seam:conversationId> </env:Header> <env:Body> <confirmAuctionResponse xmlns="http://seambay.example.seam.jboss.org/"/> </env:Body></env:Envelope>

Seam 2 Reference Guide

278

Page 284: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Let us walk through an example web service. The code in this section all comes from the seamBayexample application in Seam's /examples directory, and follows the recommended strategy asdescribed in the previous section. Let us first take a look at the web service class and one of its webservice methods:

As you can see, our web service is a stateless session bean, and is annotated using the JWSannotations from the javax.jws package, as defined by JSR-181. The @WebService annotation tellsthe container that this class implements a web service, and the @WebMethod annotation on the login() method identifies the method as a web service method. The name and serviceNameattributes in the @WebService annotation are optional.

As is required by the specification, each method that is to be exposed as a web service method mustalso be declared in the remote interface of the web service class (when the web service is a statelesssession bean). In the above example, the AuctionServiceRemote interface must declare the login() method as it is annotated as a @WebMethod.

As you can see in the above code, the web service implements a login() method that delegates toSeam's built-in Identity component. In keeping with our recommended strategy, the web service iswritten as a simple facade, passing off the real work to a Seam component. This allows for the greatestreuse of business logic between web services and other clients.

Let us look at another example. This web service method begins a new conversation by delegating tothe AuctionAction.createAuction() method:

And here is the code from AuctionAction:

@Stateless@WebService(name = "AuctionService", serviceName = "AuctionService")public class AuctionService implements AuctionServiceRemote{ @WebMethod public boolean login(String username, String password) { Identity.instance().setUsername(username); Identity.instance().setPassword(password); Identity.instance().login(); return Identity.instance().isLoggedIn(); } // snip}

@WebMethod public void createAuction(String title, String description, int categoryId) { AuctionAction action = (AuctionAction) Component.getInstance(AuctionAction.class, true); action.createAuction(); action.setDetails(title, description, categoryId); }

@Begin public void createAuction() {

CHAPTER 22. WEB SERVICES

279

Page 285: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

From this we can see how web services can participate in long running conversations, by acting as afacade and delegating the real work to a conversational Seam component.

auction = new Auction(); auction.setAccount(authenticatedAccount); auction.setStatus(Auction.STATUS_UNLISTED); durationDays = DEFAULT_AUCTION_DURATION; }

Seam 2 Reference Guide

280

Page 286: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 23. REMOTINGSeam provides a convenient method of remotely accessing components from a web page, using AJAX(Asynchronous Javascript and XML). The framework for this functionality is provided with almost noup-front development effort, your components only require simple annotating to become accessiblevia AJAX. This chapter describes the steps required to build an AJAX-enabled web page, then goes onto explain the features of the Seam Remoting framework in more detail.

23.1. CONFIGURATION

To use remoting, the Seam Resource servlet must first be configured in your web.xml file:

The next step is to import the necessary Javascript into your web page. There are a minimum of twoscripts that must be imported. The first contains all the client-side framework code that enablesremoting functionality:

The second script contains the stubs and type definitions for the components you wish to call. It isgenerated dynamically based on the local interface of your components, and includes type definitionsfor all of the classes that can be used to call the remotable methods of the interface. The name of thescript reflects the name of your component. For example, if you have a stateless session beanannotated with @Name("customerAction"), then your script tag should look like this:

If you wish to access more than one component from the same page, then include them all asparameters of your script tag:

Alternatively, you may use the s:remote tag to import the required Javascript. Separate eachcomponent or class name you wish to import with a comma:

<servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class></servlet>

<servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern></servlet-mapping>

<script type="text/javascript" src="seam/resource/remoting/resource/remote.js"></script>

<script type="text/javascript" src="seam/resource/remoting/interface.js?customerAction"></script>

<script type="text/javascript" src="seam/resource/remoting/interface.js?customerAction&accountAction"></script>

<s:remote include="customerAction,accountAction"/>

CHAPTER 23. REMOTING

281

Page 287: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

23.2. THE "SEAM" OBJECT

Client-side interaction with your components is all performed via the Seam Javascript object. Thisobject is defined in remote.js, and you'll be using it to make asynchronous calls against yourcomponent. It is split into two areas of functionality; Seam.Component contains methods for workingwith components and Seam.Remoting contains methods for executing remote requests. The easiestway to become familiar with this object is to start with a simple example.

23.2.1. A Hello World example

Let us step through a simple example to see how the Seam object works. First of all, we will create anew Seam component called helloAction.

You also need to create a local interface for our new component - take special note of the @WebRemote annotation, as it is required to make our method accessible via remoting:

That is all the server-side code we need to write. Now for our web page we will create a new page andimport the helloAction component:

To make this a fully interactive user experience, let us add a button to our page:

We will also need to add some more script to make our button actually do something when it's clicked:

@Stateless@Name("helloAction")public class HelloAction implements HelloLocal { public String sayHello(String name) { return "Hello, " + name; }}

@Localpublic interface HelloLocal { @WebRemote public String sayHello(String name);}

<s:remote include="helloAction"/>

<button onclick="javascript:sayHello()">Say Hello</button>

<script type="text/javascript"> //<![CDATA[

function sayHello() { var name = prompt("What is your name?"); Seam.Component.getInstance("helloAction").sayHello(name, sayHelloCallback); }

function sayHelloCallback(result) { alert(result); }

Seam 2 Reference Guide

282

Page 288: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

All done. Deploy your application and browse to your page. Click the button, and enter a name whenprompted. A message box will display the hello message confirming that the call was successful. If youwant to save some time, you'll find the full source code for this Hello World example in Seam's /examples/remoting/helloworld directory.

So what does the code of our script actually do? Let us break it down into smaller pieces. To start with,you can see from the Javascript code listing that we have implemented two methods - the first methodis responsible for prompting the user for their name and then making a remote request. Take a look atthe following line:

The first section of this line, Seam.Component.getInstance("helloAction") returns a proxy, orstub for our helloAction component. We can invoke the methods of our component against this stub,which is exactly what happens with the remainder of the line: sayHello(name, sayHelloCallback);.

What this line of code in its completeness does, is invoke the sayHello method of our component,passing in name as a parameter. The second parameter, sayHelloCallback is not a parameter of ourcomponent's sayHello method, instead it tells the Seam Remoting framework that once it receivesthe response to our request, it should pass it to the sayHelloCallback Javascript method. Thiscallback parameter is entirely optional, so feel free to leave it out if you're calling a method with a void return type or if you don't care about the result.

The sayHelloCallback method, once receiving the response to our remote request then pops up analert message displaying the result of our method call.

23.2.2. Seam.Component

The Seam.Component Javascript object provides a number of client-side methods for working withyour Seam components. The two main methods, newInstance() and getInstance() aredocumented in the following sections however their main difference is that newInstance() willalways create a new instance of a component type, and getInstance() will return a singletoninstance.

23.2.2.1. Seam.Component.newInstance()

Use this method to create a new instance of an entity or Javabean component. The object returned bythis method will have the same getter/setter methods as its server-side counterpart, or alternatively ifyou wish you can access its fields directly. Take the following Seam entity component for example:

// ]]></script>

Seam.Component.getInstance("helloAction").sayHello(name, sayHelloCallback);

@Name("customer")@Entitypublic class Customer implements Serializable{ private Integer customerId; private String firstName; private String lastName;

CHAPTER 23. REMOTING

283

Page 289: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

To create a client-side Customer you would write the following code:

Then from here you can set the fields of the customer object:

23.2.2.2. Seam.Component.getInstance()

The getInstance() method is used to get a reference to a Seam session bean component stub,which can then be used to remotely execute methods against your component. This method returns asingleton for the specified component, so calling it twice in a row with the same component name willreturn the same instance of the component.

To continue our example from before, if we have created a new customer and we now wish to save it,we would pass it to the saveCustomer() method of our customerAction component:

23.2.2.3. Seam.Component.getComponentName()

Passing an object into this method will return its component name if it is a component, or null if it isnot.

@Column public Integer getCustomerId() { return customerId; } public void setCustomerId(Integer customerId} { this.customerId = customerId; } @Column public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @Column public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; }}

var customer = Seam.Component.newInstance("customer");

customer.setFirstName("John");// Or you can set the fields directlycustomer.lastName = "Smith";

Seam.Component.getInstance("customerAction").saveCustomer(customer);

if (Seam.Component.getComponentName(instance) == "customer")

Seam 2 Reference Guide

284

Page 290: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

23.2.3. Seam.Remoting

Most of the client side functionality for Seam Remoting is contained within the Seam.Remotingobject. While you should not need to directly call most of its methods, there are a couple of importantones worth mentioning.

23.2.3.1. Seam.Remoting.createType()

If your application contains or uses Javabean classes that aren't Seam components, you may need tocreate these types on the client side to pass as parameters into your component method. Use the createType() method to create an instance of your type. Pass in the fully qualified Java class nameas a parameter:

23.2.3.2. Seam.Remoting.getTypeName()

This method is the equivalent of Seam.Component.getComponentName() but for non-componenttypes. It will return the name of the type for an object instance, or null if the type is not known. Thename is the fully qualified name of the type's Java class.

23.3. EVALUATING EL EXPRESSIONS

Seam Remoting also supports the evaluation of EL expressions, which provides another convenientmethod for retrieving data from the server. Using the Seam.Remoting.eval() function, an ELexpression can be remotely evaluated on the server and the resulting value returned to a client-sidecallback method. This function accepts two parameters, the first being the EL expression to evaluate,and the second being the callback method to invoke with the value of the expression. Here's anexample:

In this example, the expression #{customers} is evaluated by Seam, and the value of the expression(in this case a list of Customer objects) is returned to the customersCallback() method. It isimportant to remember that the objects returned this way must have their types imported (via s:remote) to be able to work with them in Javascript. So to work with a list of customer objects, it isrequired to import the customer type:

23.4. CLIENT INTERFACES

alert("Customer");else if (Seam.Component.getComponentName(instance) == "staff") alert("Staff member");

var widget = Seam.Remoting.createType("com.acme.widgets.MyWidget");

function customersCallback(customers) { for (var i = 0; i < customers.length; i++) { alert("Got customer: " + customers[i].getName()); } } Seam.Remoting.eval("#{customers}", customersCallback);

<s:remote include="customer"/>

CHAPTER 23. REMOTING

285

Page 291: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

In the configuration section above, the interface, or stub for our component is imported into our pageeither via seam/resource/remoting/interface.js: or using the s:remote tag:

By including this script in our page, the interface definitions for our component, plus any othercomponents or types that are required to execute the methods of our component are generated andmade available for the remoting framework to use.

There are two types of client stub that can be generated, executable stubs and type stubs. Executablestubs are behavioral, and are used to execute methods against your session bean components, whiletype stubs contain state and represent the types that can be passed in as parameters or returned as aresult.

The type of client stub that is generated depends on the type of your Seam component. If thecomponent is a session bean, then an executable stub will be generated, otherwise if it's an entity orJavaBean, then a type stub will be generated. There is one exception to this rule; if your component isa JavaBean (ie it is not a session bean nor an entity bean) and any of its methods are annotated with@WebRemote, then an executable stub will be generated for it instead of a type stub. This allows you touse remoting to call methods of your JavaBean components in a non-EJB environment where you donot have access to session beans.

23.5. THE CONTEXT

The Seam Remoting Context contains additional information which is sent and received as part of aremoting request/response cycle. At this stage it only contains the conversation ID but may beexpanded in the future.

23.5.1. Setting and reading the Conversation ID

If you intend on using remote calls within the scope of a conversation then you need to be able to reador set the conversation ID in the Seam Remoting Context. To read the conversation ID after making aremote request call Seam.Remoting.getContext().getConversationId(). To set theconversation ID before making a request, call Seam.Remoting.getContext().setConversationId().

If the conversation ID has not been explicitly set with Seam.Remoting.getContext().setConversationId(), then it will be automatically assigned thefirst valid conversation ID that is returned by any remoting call. If you are working with multipleconversations within your page, then you may need to explicitly set the conversation ID before eachcall. If you are working with just a single conversation, then you do not need to do anything special.

23.5.2. Remote calls within the current conversation scope

In some circumstances it may be required to make a remote call within the scope of the current view'sconversation. To do this, you must explicitly set the conversation ID to that of the view before makingthe remote call. This small snippet of JavaScript will set the conversation ID that is used for remotingcalls to the current view's conversation ID:

<script type="text/javascript" src="seam/resource/remoting/interface.js?customerAction"></script>

<s:remote include="customerAction"/>

Seam.Remoting.getContext().setConversationId( #{conversation.id} );

Seam 2 Reference Guide

286

Page 292: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

23.6. BATCH REQUESTS

Seam Remoting allows multiple component calls to be executed within a single request. It isrecommended that this feature is used wherever it is appropriate to reduce network traffic.

The method Seam.Remoting.startBatch() will start a new batch, and any component callsexecuted after starting a batch are queued, rather than being sent immediately. When all the desiredcomponent calls have been added to the batch, the Seam.Remoting.executeBatch() method willsend a single request containing all of the queued calls to the server, where they will be executed inorder. After the calls have been executed, a single response containing all return values will bereturned to the client and the callback functions (if provided) triggered in the same order as execution.

If you start a new batch via the startBatch() method but then decide you do not want to send it, the Seam.Remoting.cancelBatch() method will discard any calls that were queued and exit the batchmode.

To see an example of a batch being used, take a look at /examples/remoting/chatroom.

23.7. WORKING WITH DATA TYPES

23.7.1. Primitives / Basic Types

This section describes the support for basic data types. On the server side these values are generallycompatible with either their primitive type or their corresponding wrapper class.

23.7.1.1. String

Simply use Javascript String objects when setting String parameter values.

23.7.1.2. Number

There is support for all number types supported by Java. On the client side, number values are alwaysserialized as their String representation and then on the server side they are converted to the correctdestination type. Conversion into either a primitive or wrapper type is supported for Byte, Double, Float, Integer, Long and Short types.

23.7.1.3. Boolean

Booleans are represented client side by Javascript Boolean values, and server side by a Java boolean.

23.7.2. JavaBeans

In general these will be either Seam entity or JavaBean components, or some other non-componentclass. Use the appropriate method (either Seam.Component.newInstance() for Seam componentsor Seam.Remoting.createType() for everything else) to create a new instance of the object.

It is important to note that only objects that are created by either of these two methods should be usedas parameter values, where the parameter is not one of the other valid types mentioned anywhere elsein this section. In some situations you may have a component method where the exact parameter typecannot be determined, such as:

@Name("myAction")public class MyAction implements MyActionLocal {

CHAPTER 23. REMOTING

287

Page 293: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

In this case you might want to pass in an instance of your myWidget component, however the interfacefor myAction won't include myWidget as it is not directly referenced by any of its methods. To getaround this, MyWidget needs to be explicitly imported:

This will then allow a myWidget object to be created with Seam.Component.newInstance("myWidget"), which can then be passed to myAction.doSomethingWithObject().

23.7.3. Dates and Times

Date values are serialized into a String representation that is accurate to the millisecond. On the clientside, use a Javascript Date object to work with date values. On the server side, use any java.util.Date (or descendant, such as java.sql.Date or java.sql.Timestamp class.

23.7.4. Enums

On the client side, enums are treated the same as Strings. When setting the value for an enumparameter, simply use the String representation of the enum. Take the following component as anexample:

To call the paint() method with the color red, pass the parameter value as a String literal:

The inverse is also true - that is, if a component method returns an enum parameter (or contains anenum field anywhere in the returned object graph) then on the client-side it will be represented as aString.

23.7.5. Collections

23.7.5.1. Bags

Bags cover all collection types including arrays, collections, lists, sets, (but excluding Maps - see thenext section for those), and are implemented client-side as a Javascript array. When calling acomponent method that accepts one of these types as a parameter, your parameter should be a

public void doSomethingWithObject(Object obj) { // code }}

<s:remote include="myAction,myWidget"/>

@Name("paintAction")public class paintAction implements paintLocal { public enum Color {red, green, blue, yellow, orange, purple};

public void paint(Color color) { // code } }

Seam.Component.getInstance("paintAction").paint("red");

Seam 2 Reference Guide

288

Page 294: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Javascript array. If a component method returns one of these types, then the return value will also be aJavascript array. The remoting framework is clever enough on the server side to convert the bag to anappropriate type for the component method call.

23.7.5.2. Maps

As there is no native support for Maps within Javascript, a simple Map implementation is provided withthe Seam Remoting framework. To create a Map which can be used as a parameter to a remote call,create a new Seam.Remoting.Map object:

This Javascript implementation provides basic methods for working with Maps: size(), isEmpty(), keySet(), values(), get(key), put(key, value), remove(key) and contains(key). Each ofthese methods are equivalent to their Java counterpart. Where the method returns a collection, suchas keySet() and values(), a Javascript Array object will be returned that contains the key or valueobjects (respectively).

23.8. DEBUGGING

To aid in tracking down bugs, it is possible to enable a debug mode which will display the contents of allthe packets send back and forth between the client and server in a popup window. To enable debugmode, either execute the setDebug() method in Javascript:

Or configure it via components.xml:

To turn off debugging, call setDebug(false). If you want to write your own messages to the debuglog, call Seam.Remoting.log(message).

23.9. THE LOADING MESSAGE

The default loading message that appears in the top right corner of the screen can be modified, itsrendering customized or even turned off completely.

23.9.1. Changing the message

To change the message from the default Please Wait... to something different, set the value of Seam.Remoting.loadingMessage:

23.9.2. Hiding the loading message

To completely suppress the display of the loading message, override the implementation of displayLoadingMessage() and hideLoadingMessage() with functions that instead do nothing:

var map = new Seam.Remoting.Map();

Seam.Remoting.setDebug(true);

<remoting:remoting debug="true"/>

Seam.Remoting.loadingMessage = "Loading...";

CHAPTER 23. REMOTING

289

Page 295: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

23.9.3. A Custom Loading Indicator

It is also possible to override the loading indicator to display an animated icon, or anything else thatyou want. To do this override the displayLoadingMessage() and hideLoadingMessage()messages with your own implementation:

23.10. CONTROLLING WHAT DATA IS RETURNED

When a remote method is executed, the result is serialized into an XML response that is returned tothe client. This response is then unmarshaled by the client into a Javascript object. For complex types(for instance, Javabeans) that include references to other objects, all of these referenced objects arealso serialized as part of the response. These objects may reference other objects, which mayreference other objects, and so forth. If left unchecked, this object graph could potentially beenormous, depending on what relationships exist between your objects. And as a side issue (besidesthe potential verbosity of the response), you might also wish to prevent sensitive information frombeing exposed to the client.

Seam Remoting provides a simple means to "constrain" the object graph, by specifying the excludefield of the remote method's @WebRemote annotation. This field accepts a String array containing oneor more paths specified using dot notation. When invoking a remote method, the objects in the result'sobject graph that match these paths are excluded from the serialized result packet.

For all our examples, we'll use the following Widget class:

23.10.1. Constraining normal fields

If your remote method returns an instance of Widget, but you don't want to expose the secret fieldbecause it contains sensitive information, you would constrain it like this:

// don't display the loading indicatorSeam.Remoting.displayLoadingMessage = function() {};Seam.Remoting.hideLoadingMessage = function() {};

Seam.Remoting.displayLoadingMessage = function() { // Write code here to display the indicator }; Seam.Remoting.hideLoadingMessage = function() { // Write code here to hide the indicator };

@Name("widget")public class Widget{ private String value; private String secret; private Widget child; private Map<String,Widget> widgetMap; private List<Widget> widgetList; // getters and setters for all fields}

Seam 2 Reference Guide

290

Page 296: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The value "secret" refers to the secret field of the returned object. Now, suppose that we don't careabout exposing this particular field to the client. Instead, notice that the Widget value that is returnedhas a field child that is also a Widget. What if we want to hide the child's secret value instead?We can do this by using dot notation to specify this field's path within the result's object graph:

23.10.2. Constraining Maps and Collections

The other place that objects can exist within an object graph are within a Map or some kind ofcollection (List, Set, Array, etc). Collections are easy, and are treated like any other field. Forexample, if our Widget contained a list of other Widgets in its widgetList field, to constrain the secret field of the Widgets in this list the annotation would look like this:

To constrain a Map's key or value, the notation is slightly different. Appending [key] after the Map'sfield name will constrain the Map's key object values, while [value] will constrain the value objectvalues. The following example demonstrates how the values of the widgetMap field have their secretfield constrained:

23.10.3. Constraining objects of a specific type

There is one last notation that can be used to constrain the fields of a type of object no matter where inthe result's object graph it appears. This notation uses either the name of the component (if the objectis a Seam component) or the fully qualified class name (only if the object is not a Seam component) andis expressed using square brackets:

23.10.4. Combining Constraints

Constraints can also be combined, to filter objects from multiple paths within the object graph:

23.11. JMS MESSAGING

Seam Remoting provides experimental support for JMS Messaging. This section describes the JMSsupport that is currently implemented, but please note that this may change in the future. It iscurrently not recommended that this feature is used within a production environment.

@WebRemote(exclude = {"secret"})public Widget getWidget();

@WebRemote(exclude = {"child.secret"})public Widget getWidget();

@WebRemote(exclude = {"widgetList.secret"})public Widget getWidget();

@WebRemote(exclude = {"widgetMap[value].secret"})public Widget getWidget();

@WebRemote(exclude = {"[widget].secret"})public Widget getWidget();

@WebRemote(exclude = {"widgetList.secret", "widgetMap[value].secret"})public Widget getWidget();

CHAPTER 23. REMOTING

291

Page 297: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

23.11.1. Configuration

Before you can subscribe to a JMS topic, you must first configure a list of the topics that can besubscribed to by Seam Remoting. List the topics under org.jboss.seam.remoting.messaging.subscriptionRegistry.allowedTopics in seam.properties, web.xml or components.xml.

23.11.2. Subscribing to a JMS Topic

The following example demonstrates how to subscribe to a JMS Topic:

The Seam.Remoting.subscribe() method accepts two parameters, the first being the name of theJMS Topic to subscribe to, the second being the callback function to invoke when a message isreceived.

There are two types of messages supported, Text messages and Object messages. If you need to testfor the type of message that is passed to your callback function you can use the instanceof operatorto test whether the message is a Seam.Remoting.TextMessage or Seam.Remoting.ObjectMessage. A TextMessage contains the text value in its text field (oralternatively call getText() on it), while an ObjectMessage contains its object value in its valuefield (or call its getValue() method).

23.11.3. Unsubscribing from a Topic

To unsubscribe from a topic, call Seam.Remoting.unsubscribe() and pass in the topic name:

23.11.4. Tuning the Polling Process

There are two parameters which you can modify to control how polling occurs. The first one is Seam.Remoting.pollInterval, which controls how long to wait between subsequent polls for newmessages. This parameter is expressed in seconds, and its default setting is 10.

The second parameter is Seam.Remoting.pollTimeout, and is also expressed as seconds. Itcontrols how long a request to the server should wait for a new message before timing out and sendingan empty response. Its default is 0 seconds, which means that when the server is polled, if there are nomessages ready for delivery then an empty response will be immediately returned.

Caution should be used when setting a high pollTimeout value; each request that has to wait for amessage means that a server thread is tied up until a message is received, or until the request timesout. If many such requests are being served simultaneously, it could mean a large number of threadsbecome tied up because of this reason.

<remoting:remoting poll-timeout="5" poll-interval="1"/>

function subscriptionCallback(message){ if (message instanceof Seam.Remoting.TextMessage) alert("Received message: " + message.getText());}

Seam.Remoting.subscribe("topicName", subscriptionCallback);

Seam.Remoting.unsubscribe("topicName");

Seam 2 Reference Guide

292

Page 298: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

It is recommended that you set these options via components.xml, however they can be overriddenvia Javascript if desired. The following example demonstrates how to configure the polling to occurmuch more aggressively. You should set these parameters to suitable values for your application:

Via components.xml:

Via JavaScript:

<remoting:remoting poll-timeout="5" poll-interval="1"/>

// Only wait 1 second between receiving a poll response and sending the next poll request.Seam.Remoting.pollInterval = 1; // Wait up to 5 seconds on the server for new messagesSeam.Remoting.pollTimeout = 5;

CHAPTER 23. REMOTING

293

Page 299: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 24. SPRING FRAMEWORK INTEGRATIONThe Spring integration module allows easy migration of Spring-based projects to Seam and allowsSpring applications to take advantage of key Seam features like conversations and Seam's moresophisticated persistence context management.

NOTE

Spring integration in Seam is marked as technology preview, so standard support is notguaranteed.

NOTE

The Spring integration code is included in the jboss-seam-ioc library. Thisdependency is required for all seam-spring integration techniques covered in thischapter.

Seam's support for Spring provides the ability to:

inject Seam component instances into Spring beans

inject Spring beans into Seam components

turn Spring beans into Seam components

allow Spring beans to live in any Seam context

start a spring WebApplicationContext with a Seam component

Support for Spring PlatformTransactionManagement

provides a Seam managed replacement for Spring's OpenEntityManagerInViewFilter andOpenSessionInViewFilter

Support for Spring TaskExecutors to back @Asynchronous calls

24.1. INJECTING SEAM COMPONENTS INTO SPRING BEANS

Injecting Seam component instances into Spring beans is accomplished using the <seam:instance/> namespace handler. To enable the Seam namespace handler, the Seamnamespace must be added to the Spring beans definition file:

Now any Seam component may be injected into any Spring bean:

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:seam="http://jboss.com/products/seam/spring-seam" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://jboss.com/products/seam/spring-seam http://jboss.com/products/seam/spring-seam-2.1.xsd">

Seam 2 Reference Guide

294

Page 300: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

An EL expression may be used instead of a component name:

Seam component instances may even be made available for injection into Spring beans by a Springbean ID.

Unlike Seam bijection, Spring injection does not occur at method invocation time. Instead, injectionhappens only when the Spring bean is instantiated. So the instance available when the bean isinstantiated will be the same instance that the bean uses for the entire life of the bean. For example, ifa Seam CONVERSATION-scoped component instance is directly injected into a singleton Spring bean,that singleton will hold a reference to the same instance long after the conversation is over. We callthis problem scope impedance. Seam bijection ensures that scope impedance is maintained naturally asan invocation flows through the system. In Spring, we need to inject a proxy of the Seam component,and resolve the reference when the proxy is invoked.

The <seam:instance/> tag lets us automatically proxy the Seam component.

This example shows one way to use a Seam-managed persistence context from a Spring bean. (For amore robust way to use Seam-managed persistence contexts as a replacement for the Spring OpenEntityManagerInView filter see section on Section 24.6, “Using a Seam Managed PersistenceContext in Spring”Using a Seam Managed Persistence Context in Spring)

24.2. INJECTING SPRING BEANS INTO SEAM COMPONENTS

It is even easier to inject Spring beans into Seam component instances. Actually, there are two possibleapproaches:

inject a Spring bean using an EL expression

make the Spring bean a Seam component

<bean id="someSpringBean" class="SomeSpringBeanClass" scope="prototype"> <property name="someProperty"> <seam:instance name="someComponent"/> </property></bean>

<bean id="someSpringBean" class="SomeSpringBeanClass" scope="prototype"> <property name="someProperty"> <seam:instance name="#{someExpression}"/> </property></bean>

<seam:instance name="someComponent" id="someSeamComponentInstance"/>

<bean id="someSpringBean" class="SomeSpringBeanClass" scope="prototype"> <property name="someProperty" ref="someSeamComponentInstance"></bean>

<seam:instance id="seamManagedEM" name="someManagedEMComponent" proxy="true"/>

<bean id="someSpringBean" class="SomeSpringBeanClass"> <property name="entityManager" ref="seamManagedEM"></bean>

CHAPTER 24. SPRING FRAMEWORK INTEGRATION

295

Page 301: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We will discuss the second option in the next section. The easiest approach is to access the Springbeans via EL.

The Spring DelegatingVariableResolver is an integration point Spring provides for integratingSpring with JSF. This VariableResolver makes all Spring beans available in EL by their bean ID. Youwill need to add the DelegatingVariableResolver to faces-config.xml:

Then you can inject Spring beans using @In:

The use of Spring beans in EL is not limited to injection. Spring beans may be used anywhere that ELexpressions are used in Seam: process and pageflow definitions, working memory assertions, etc...

24.3. MAKING A SPRING BEAN INTO A SEAM COMPONENT

The <seam:component/> namespace handler can be used to make any Spring bean a Seamcomponent. Just place the <seam:component/> tag within the declaration of the bean that you wishto be a Seam component:

By default, <seam:component/> will create a STATELESS Seam component with class and nameprovided in the bean definition. Occasionally, such as when a FactoryBean is used, the class of theSpring bean may not be the class appearing in the bean definition. In such cases the class should beexplicitly specified. A Seam component name may be explicitly specified in cases where there ispotential for a naming conflict.

The scope attribute of <seam:component/> may be used if you wish the Spring bean to be managedin a particular Seam scope. The Spring bean must be scoped to prototype if the Seam scope specifiedis anything other than STATELESS. Pre-existing Spring beans usually have a fundamentally statelesscharacter, so this attribute is not usually needed.

24.4. SEAM-SCOPED SPRING BEANS

The Seam integration package also lets you use Seam's contexts as Spring 2.0 style custom scopes.This lets you declare any Spring bean in any of Seam's contexts. However, note once again thatSpring's component model was never architectured to support statefulness, so please use this featurewith great care. In particular, clustering of session or conversation scoped Spring beans is deeplyproblematic, and care must be taken when injecting a bean or component from a wider scope into abean of a narrower scope.

<application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver></application>

@In("#{bookingService}")private BookingService bookingService;

<bean id="someSpringBean" class="SomeSpringBeanClass" scope="prototype"> <seam:component/></bean>

Seam 2 Reference Guide

296

Page 302: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

By specifying <seam:configure-scopes/> once in a Spring bean factory configuration, all of theSeam scopes will be available to Spring beans as custom scopes. To associate a Spring bean with aparticular Seam scope, specify the Seam scope in the scope attribute of the bean definition.

The prefix of the scope name may be changed by specifying the prefix attribute in the configure-scopes definition. (The default prefix is seam.)

By default an instance of a Spring Component registered in this way is not automatically created whenreferenced using @In. To have an instance auto-created you must either specify @In(create=true)at the injection point to identify a specific bean to be auto created or you can use the default-auto-create attribute of configure-scopes to make all spring beans who use a seam scope autocreated.

Seam-scoped Spring beans defined this way can be injected into other Spring beans without the use of <seam:instance/>. However, care must be taken to ensure scope impedance is maintained. Thenormal approach used in Spring is to specify <aop:scoped-proxy/> in the bean definition. However,Seam-scoped Spring beans are not compatible with <aop:scoped-proxy/>. So if you need to inject aSeam-scoped Spring bean into a singleton, <seam:instance/> must be used:

24.5. USING SPRING PLATFORMTRANSACTIONMANAGEMENT

Spring provides an extensible transaction management abstraction with support for many transactionAPIs (JPA, Hibernate, JDO, and JTA) Spring also provides tight integrations with many applicationserver TransactionManagers such as Websphere and Weblogic. Spring transaction managementexposes support for many advanced features such as nested transactions and supports full Java EEtransaction propagation rules like REQUIRES_NEW and NOT_SUPPORTED. For more information seethe spring documentation here.

To configure Seam to use Spring transactions enable the SpringTransaction component like so:

The spring:spring-transaction component will utilize Springs transaction synchronizationcapabilities for synchronization callbacks.

<!-- Only needs to be specified once per bean factory--><seam:configure-scopes/>

...

<bean id="someSpringBean" class="SomeSpringBeanClass" scope="seam.CONVERSATION"/>

<bean id="someSpringBean" class="SomeSpringBeanClass" scope="seam.CONVERSATION"/>

...

<bean id="someSingleton"> <property name="someSeamScopedSpringBean"> <seam:instance name="someSpringBean" proxy="true"/> </property></bean>

<spring:spring-transaction platform-transaction-manager="#{transactionManager}"/>

CHAPTER 24. SPRING FRAMEWORK INTEGRATION

297

Page 303: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

24.6. USING A SEAM MANAGED PERSISTENCE CONTEXT IN SPRING

One of the most powerful features of Seam is its conversation scope and the ability to have anEntityManager open for the life of a conversation. This eliminates many of the problems associatedwith the detachment and re-attachment of entities as well as mitigates occurrences of the dreaded LazyInitializationException. Spring does not provide a way to manage an persistence contextbeyond the scope of a single web request (OpenEntityManagerInViewFilter). So, it would be niceif Spring developers could have access to a Seam managed persistence context using all of the sametools Spring provides for integration with JPA(for example, PersistenceAnnotationBeanPostProcessor, JpaTemplate, etc.)

Seam provides a way for Spring to access a Seam managed persistence context with Spring's providedJPA tools bringing conversation scoped persistence context capabilities to Spring applications.

This integration work provides the following functionality:

transparent access to a Seam managed persistence context using Spring provided tools

access to Seam conversation scoped persistence contexts in a non web request (for example,asynchronous quartz job)

allows for using Seam managed persistence contexts with Spring managed transactions (willneed to flush the persistence context manually)

Spring's persistence context propagation model allows only one open EntityManager perEntityManagerFactory so the Seam integration works by wrapping an EntityManagerFactory around aSeam managed persistence context.

Where persistenceContextName is the name of the Seam managed persistence contextcomponent. By default this EntityManagerFactory has a unitName equal to the Seam componentname or in this case entityManager. If you wish to provide a different unitName you can do so byproviding a persistenceUnitName like so:

This EntityManagerFactory can then be used in any Spring provided tools. For example, usingSpring's PersistenceAnnotationBeanPostProcessor is the exact same as before.

If you define your real EntityManagerFactory in Spring but wish to use a Seam managedpersistence context you can tell the PersistenceAnnotationBeanPostProcessor which persistenctUnitName you wish to use by default by specifying the

<bean id="seamEntityManagerFactory" class="org.jboss.seam.ioc.spring.SeamManagedEntityManagerFactoryBean"> <property name="persistenceContextName" value="entityManager"/></bean>

<bean id="seamEntityManagerFactory" class="org.jboss.seam.ioc.spring.SeamManagedEntityManagerFactoryBean"> <property name="persistenceContextName" value="entityManager"/> <property name="persistenceUnitName" value="bookingDatabase:extended"/></bean>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

Seam 2 Reference Guide

298

Page 304: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

defaultPersistenceUnitName property.

The applicationContext.xml might look like:

The component.xml might look like:

JpaTemplate and JpaDaoSupport are configured the same way for a Seam managed persistencecontext as they would be fore a Seam managed persistence context.

24.7. USING A SEAM MANAGED HIBERNATE SESSION IN SPRING

The Seam Spring integration also provides support for complete access to a Seam managed Hibernatesession using spring's tools. This integration is very similar to the Section 24.6, “Using a SeamManaged Persistence Context in Spring”JPA integration.

Like Spring's JPA integration, Spring's propagation model allows only one open EntityManager perEntityManagerFactory per transaction to be available to spring tools. So, the Seam Session integrationworks by wrapping a proxy SessionFactory around a Seam managed Hibernate session context.

Where sessionName is the name of the persistence:managed-hibernate-session component.This SessionFactory can then be used in any Spring provided tools. The integration also providessupport for calls to SessionFactory.getCurrentInstance() as long as you callgetCurrentInstance() on the SeamManagedSessionFactory.

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="bookingDatabase"/></bean><bean id="seamEntityManagerFactory" class="org.jboss.seam.ioc.spring.SeamManagedEntityManagerFactoryBean"> <property name="persistenceContextName" value="entityManager"/> <property name="persistenceUnitName" value="bookingDatabase:extended"/></bean><bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> <property name="defaultPersistenceUnitName" value="bookingDatabase:extended"/></bean>

<persistence:managed-persistence-context name="entityManager" auto-create="true" entity-manager-factory="#{entityManagerFactory}"/>

<bean id="bookingService" class="org.jboss.seam.example.spring.BookingService"> <property name="entityManagerFactory" ref="seamEntityManagerFactory"/></bean>

<bean id="seamSessionFactory" class="org.jboss.seam.ioc.spring.SeamManagedSessionFactoryBean"> <property name="sessionName" value="hibernateSession"/></bean>

CHAPTER 24. SPRING FRAMEWORK INTEGRATION

299

Page 305: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

24.8. SPRING APPLICATION CONTEXT AS A SEAM COMPONENT

Although it is possible to use the Spring ContextLoaderListener to start your application's SpringApplicationContext there are a couple of limitations.

the Spring ApplicationContext must be started after the SeamListener

it can be tricky starting a Spring ApplicationContext for use in Seam unit and integration tests

To overcome these two limitations the Spring integration includes a Seam component that will start aSpring ApplicationContext. To use this Seam component place the <spring:context-loader/>definition in the components.xml. Specify your Spring context file location in the config-locations attribute. If more than one config file is needed you can place them in the nested <spring:config-locations/> element following standard components.xml multi valuepractices.

24.9. USING A SPRING TASKEXECUTOR FOR @ASYNCHRONOUS

Spring provides an abstraction for executing code asynchronously called a TaskExecutor. The SpringSeam integration allows for the use of a Spring TaskExecutor for executing immediate @Asynchronous method calls. To enable this functionality install the SpringTaskExecutorDispatchor and provide a spring bean defined taskExecutor like so:

Because a Spring TaskExecutor does not support scheduling of an asynchronous event a fallbackSeam Dispatcher can be provided to handle scheduled asynchronous event like so:

<components xmlns="http://jboss.com/products/seam/components" xmlns:spring="http://jboss.com/products/seam/spring" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jboss.com/products/seam/components http://jboss.com/products/seam/components-2.1.xsd http://jboss.com/products/seam/spring http://jboss.com/products/seam/spring-2.1.xsd">

<spring:context-loader config-locations="/WEB-INF/applicationContext.xml"/>

</components>

<spring:task-executor-dispatcher task-executor="#{springThreadPoolTaskExecutor}"/>

<!-- Install a ThreadPoolDispatcher to handle scheduled asynchronous event --><core:thread-pool-dispatcher name="threadPoolDispatcher"/>

<!-- Install the SpringDispatcher as default --><spring:task-executor-dispatcher task-executor="#{springThreadPoolTaskExecutor}" schedule-dispatcher="#{threadPoolDispatcher}"/>

Seam 2 Reference Guide

300

Page 306: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 25. HIBERNATE SEARCH

25.1. INTRODUCTION

Full text search engines like Apache Lucene are a very powerful technology that bring full text andefficient queries to applications. Hibernate Search, which uses Apache Lucene under the covers,indexes your domain model with the addition of a few annotations, takes care of the database / indexsynchronization and returns regular managed objects that are matched by full text queries. Keep inmind, thought, that there are mismatches that arise when dealing with an object domain model over atext index (keeping the index up to date, mismatch between the index structure and the domain model,and querying mismatch). But the benefits of speed and efficiency far outweigh these limitations.

Hibernate Search has been designed to integrates nicely and as naturally as possible with JPA andHibernate. As a natural extension, JBoss Seam provides an Hibernate Search integration.

Please refer to the Hibernate Search documentation for information specific to the Hibernate Searchproject.

NOTE

Hibernate Search integration in Seam is marked as technology preview, so standardsupport is not guaranteed.

25.2. CONFIGURATION

Hibernate Search is configured either in the META-INF/persistence.xml or hibernate.cfg.xmlfile.

Hibernate Search configuration has sensible defaults for most configuration parameters. Here is aminimal persistence unit configuration to get started.

If you plan to target Hibernate Annotations or EntityManager 3.2.x (embedded into JBoss EAP AS 4.3),you also need to configure the appropriate event listeners.

<persistence-unit name="sample"> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> [...] <!-- use a file system based index --> <property name="hibernate.search.default.directory_provider" value="org.hibernate.search.store.FSDirectoryProvider"/> <!-- directory where the indexes will be stored --> <property name="hibernate.search.default.indexBase" value="/Users/prod/apps/dvdstore/dvdindexes"/> </properties></persistence-unit>

<persistence-unit name="sample"> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> [...] <!-- use a file system based index --> <property name="hibernate.search.default.directory_provider"

CHAPTER 25. HIBERNATE SEARCH

301

Page 307: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

NOTE

This step is no longer necessary if Hibernate Annotation or EntityManager 3.3.x areused.

In addition to the configuration file, the following jars have to be deployed:

hibernate-search.jar

hibernate-commons-annotations.jar

lucene-core.jar

NOTE

If you deploy those in a EAR, do not forget to update application.xml

25.3. USAGE

Hibernate Search uses annotations to map entities to a Lucene index, check the referencedocumentation for more information.

Hibernate Search is fully integrated with the API and semantic of JPA / Hibernate. Switching from aHQL or Criteria based query requires just a few lines of code. The main API the application interactswith is the FullTextSession API (subclass of Hibernate's Session).

When Hibernate Search is present, JBoss Seam injects a FullTextSession.

value="org.hibernate.search.store.FSDirectoryProvider"/> <!-- directory where the indexes will be stored --> <property name="hibernate.search.default.indexBase" value="/Users/prod/apps/dvdstore/dvdindexes"/>

<property name="hibernate.ejb.event.post-insert" value="org.hibernate.search.event.FullTextIndexEventListener"/> <property name="hibernate.ejb.event.post-update" value="org.hibernate.search.event.FullTextIndexEventListener"/> <property name="hibernate.ejb.event.post-delete" value="org.hibernate.search.event.FullTextIndexEventListener"/>

</properties></persistence-unit>

@Stateful@Name("search")public class FullTextSearchAction implements FullTextSearch, Serializable {

@In FullTextSession session;

public void search(String searchString) {

Seam 2 Reference Guide

302

Page 308: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

NOTE

FullTextSession extends org.hibernate.Session so that it can be used as aregular Hibernate Session

If the Java Persistence API is used, a smoother integration is proposed.

When Hibernate Search is present, a FulltextEntityManager is injected. FullTextEntityManager extends EntityManager with search specific methods, the same way FullTextSession extends Session.

When an EJB 3.0 Session or Message Driven Bean injection is used (for instance, via the@PersistenceContext annotation), it is not possible to replace the EntityManager interface by the FullTextEntityManager interface in the declaration statement. However, the implementationinjected will be a FullTextEntityManager implementation: downcasting is then possible.

org.apache.lucene.query.Query luceneQuery = getLuceneQuery(); org.hibernate.Query query session.createFullTextQuery(luceneQuery, Product.class); searchResults = query .setMaxResults(pageSize + 1) .setFirstResult(pageSize * currentPage) .list(); } [...]}

@Stateful@Name("search")public class FullTextSearchAction implements FullTextSearch, Serializable { @In FullTextEntityManager em;

public void search(String searchString) { org.apache.lucene.query.Query luceneQuery = getLuceneQuery(); javax.persistence.Query query = em.createFullTextQuery(luceneQuery, Product.class); searchResults = query .setMaxResults(pageSize + 1) .setFirstResult(pageSize * currentPage) .getResultList(); } [...]}

@Stateful@Name("search")public class FullTextSearchAction implements FullTextSearch, Serializable { @PersistenceContext EntityManager em;

public void search(String searchString) {

CHAPTER 25. HIBERNATE SEARCH

303

Page 309: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

IMPORTANT

For people accustomed to Hibernate Search out of Seam, note that using Search.createFullTextSession is not necessary.

Check the DVDStore or the blog examples of the JBoss Seam distribution for a concrete use ofHibernate Search.

org.apache.lucene.query.Query luceneQuery = getLuceneQuery(); FullTextEntityManager ftEm = (FullTextEntityManager) em; javax.persistence.Query query = ftEm.createFullTextQuery(luceneQuery, Product.class); searchResults = query .setMaxResults(pageSize + 1) .setFirstResult(pageSize * currentPage) .getResultList(); } [...]}

Seam 2 Reference Guide

304

Page 310: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAMAPPLICATIONSConfiguration is a very boring topic and an extremely tedious pastime. Unfortunately, several lines ofXML are required to integrate Seam into your JSF implementation and servlet container. There is noneed to be too put off by the following sections; you will never need to type any of this stuff yourself,since you can just copy and paste from the example applications.

26.1. BASIC SEAM CONFIGURATION

First, let us look at the basic configuration that is needed whenever we use Seam with JSF.

26.1.1. Integrating Seam with JSF and your servlet container

You will need a faces servlet.

(You can adjust the URL pattern to suit your taste.)

In addition, Seam requires the following entry in your web.xml file:

This listener is responsible for bootstrapping Seam, and for destroying session and applicationcontexts.

Some JSF implementations have a broken implementation of server-side state saving that interfereswith Seam's conversation propagation. If you have problems with conversation propagation duringform submissions, try switching to client-side state saving. You will need this in web.xml:

There is a minor gray area in the JSF specification regarding the mutability of view state values. SinceSeam uses the JSF view state to back its PAGE scope this can become an issue in some cases. If youare using server side state saving with the JSF-RI and you want a PAGE scoped bean to keep its exactvalue for a given view of a page you will need to specify the following context-param. Otherwise if a

<servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet>

<servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.seam</url-pattern></servlet-mapping>

<listener> <listener-class>org.jboss.seam.servlet.SeamListener</listener-class></listener>

<context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value></context-param>

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

305

Page 311: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

user uses the back button a PAGE scoped component will have the latest value if it has changed not thevalue of the back page. (see Spec Issue ). This setting is not enabled by default because of theperformance hit of serializing the JSF view with every request.

26.1.2. Using facelets

If you want follow our advice and use facelets instead of JSP, add the following lines to faces-config.xml:

And the following lines to web.xml:

26.1.3. Seam Resource Servlet

The Seam Resource Servlet provides resources used by Seam Remoting, captchas (see the securitychapter) and some JSF UI controls. Configuring the Seam Resource Servlet requires the followingentry in web.xml:

26.1.4. Seam servlet filters

Seam does not need any servlet filters for basic operation. However, there are several features whichdepend upon the use of filters. To make things easier, Seam lets you add and configure servlet filtersjust like you would configure other built-in Seam components. To take advantage of this feature, wemust first install a master filter in web.xml:

<context-param> <param-name>com.sun.faces.serializeServerState</param-name> <param-value>true</param-value></context-param>

<application> <view-handler>com.sun.facelets.FaceletViewHandler</view-handler></application>

<context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value></context-param>

<servlet> <servlet-name>Seam Resource Servlet</servlet-name> <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class></servlet> <servlet-mapping> <servlet-name>Seam Resource Servlet</servlet-name> <url-pattern>/seam/resource/*</url-pattern></servlet-mapping>

<filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class>

Seam 2 Reference Guide

306

Page 312: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The Seam master filter must be the first filter specified in web.xml. This ensures it is run first.

The Seam filters share a number of common attributes, you can set these in components.xml inaddition to any parameters discussed below:

url-pattern — Used to specify which requests are filtered, the default is all requests. url-pattern is a Tomcat style pattern which allows a wildcard suffix.

regex-url-pattern — Used to specify which requests are filtered, the default is all requests. regex-url-pattern is a true regular expression match for request path. It is worth notingwhen composing the regular expression that the request path does not contain the server orrequest context path.

disabled — Used to disable a built in filter.

Adding the master filter enables the following built-in filters.

26.1.4.1. Exception handling

This filter provides the exception mapping functionality in pages.xml (almost all applications willneed this). It also takes care of rolling back uncommitted transactions when uncaught exceptionsoccur. (According to the Java EE specification, the web container should do this automatically, but wehave found that this behavior cannot be relied upon in all application servers. And it is certainly notrequired of plain servlet engines like Tomcat.)

By default, the exception handling filter will process all requests, however this behavior may beadjusted by adding a <web:exception-filter> entry to components.xml, as shown in thisexample:

26.1.4.2. Conversation propagation with redirects

This filter allows Seam to propagate the conversation context across browser redirects. It interceptsany browser redirects and adds a request parameter that specifies the Seam conversation identifier.

The redirect filter will process all requests by default, but this behavior can also be adjusted in components.xml:

26.1.4.3. Multipart form submissions

</filter>

<filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

<components xmlns="http://jboss.com/products/seam/components" xmlns:web="http://jboss.com/products/seam/web">

<web:exception-filter url-pattern="*.seam"/>

</components>

<web:redirect-filter url-pattern="*.seam"/>

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

307

Page 313: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This feature is necessary when using the Seam file upload JSF control. It detects multipart formrequests and processes them according to the multipart/form-data specification (RFC-2388). Tooverride the default settings, add the following entry to components.xml:

create-temp-files — If set to true, uploaded files are written to a temporary file (instead ofheld in memory). This may be an important consideration if large file uploads are expected.The default setting is false.

max-request-size — If the size of a file upload request (determined by reading the Content-Length header in the request) exceeds this value, the request will be aborted. Thedefault setting is 0 (no size limit).

26.1.4.4. Character encoding

Sets the character encoding of submitted form data.

This filter is not installed by default and requires an entry in components.xml to enable it:

encoding — The encoding to use.

override-client — If this is set to true, the request encoding will be set to whatever isspecified by encoding no matter whether the request already specifies an encoding or not. Ifset to false, the request encoding will only be set if the request doesn't already specify anencoding. The default setting is false.

26.1.4.5. RichFaces

If RichFaces is used in your project, Seam will install the RichFaces Ajax filter for you, making sure toinstall it before all other built-in filters. You do not need to install the RichFaces Ajax filter in web.xmlyourself.

The RichFaces Ajax filter is only installed if the RichFaces jars are present in your project.

To override the default settings, add the following entry to components.xml. The options are thesame as those specified in the RichFaces Developer Guide:

force-parser — forces all JSF pages to be validated by Richfaces's XML syntax checker. If false, only AJAX responses are validated and converted to well-formed XML. Setting force-parser to false improves performance, but can provide visual artifacts on AJAX updates.

<web:multipart-filter create-temp-files="true" max-request-size="1000000" url-pattern="*.seam"/>

<web:character-encoding-filter encoding="UTF-16" override-client="true" url-pattern="*.seam"/>

<web:ajax4jsf-filter force-parser="true" enable-cache="true" log4j-init-file="custom-log4j.xml" url-pattern="*.seam"/>

Seam 2 Reference Guide

308

Page 314: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

enable-cache — enables caching of framework-generated resources (e.g. javascript, CSS,images, etc). When developing custom javascript or CSS, setting to true prevents the browserfrom caching the resource.

log4j-init-file — is used to setup per-application logging. A path, relative to webapplication context, to the log4j.xml configuration file should be provided.

26.1.4.6. Identity Logging

This filter adds the authenticated user name to the log4j mapped diagnostic context so that it can beincluded in formatted log output if desired, by adding %X{username} to the pattern.

By default, the logging filter will process all requests, however this behavior may be adjusted by addinga <web:logging-filter> entry to components.xml, as shown in this example:

26.1.4.7. Context management for custom servlets

Requests sent direct to some servlet other than the JSF servlet are not processed through the JSFlifecycle, so Seam provides a servlet filter that can be applied to any other servlet that needs access toSeam components.

This filter allows custom servlets to interact with the Seam contexts. It sets up the Seam contexts atthe beginning of each request, and tears them down at the end of the request. You should make surethat this filter is never applied to the JSF FacesServlet. Seam uses the phase listener for contextmanagement in a JSF request.

This filter is not installed by default and requires an entry in components.xml to enable it:

The context filter expects to find the conversation id of any conversation context in a requestparameter named conversationId. You are responsible for ensuring that it gets sent in the request.

You are also responsible for ensuring propagation of any new conversation ID back to the client. Seamexposes the conversation id as a property of the built in component conversation.

26.1.4.8. Adding custom filters

Seam can install your filters for you, allowing you to specify where in the chain your filter is placed (theservlet specification doesn't provide a well defined order if you specify your filters in a web.xml). Justadd the @Filter annotation to your Seam component (which must implement javax.servlet.Filter):

<components xmlns="http://jboss.com/products/seam/components" xmlns:web="http://jboss.com/products/seam/web"> <web:logging-filter url-pattern="*.seam"/></components>

<web:context-filter url-pattern="/media/*"/>

@Startup@Scope(APPLICATION)@Name("org.jboss.seam.web.multipartFilter")@BypassInterceptors@Filter(within="org.jboss.seam.web.ajax4jsfFilter")public class MultipartFilter extends AbstractFilter {

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

309

Page 315: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Adding the @Startup annotation means that the component is available during Seam startup;bijection isn't available here (@BypassInterceptors); and the filter should be further down the chainthan the RichFaces filter (@Filter(within="org.jboss.seam.web.ajax4jsfFilter")).

26.1.5. Integrating Seam with your EJB container

We need to apply the SeamInterceptor to our Seam components. The simplest way to do this acrossan entire application is to add the following interceptor configuration in ejb-jar.xml:

Seam needs to know where to go to find session beans in JNDI. One way to do this is specify the @JndiName annotation on every session bean Seam component. However, this is quite tedious. Abetter approach is to specify a pattern that Seam can use to calculate the JNDI name from the EJBname. Unfortunately, there is no standard mapping to global JNDI defined in the EJB3 specification, sothis mapping is vendor-specific. We usually specify this option in components.xml.

For JBoss AS, the following pattern is correct:

Where myEarName is the name of the EAR in which the bean is deployed.

Outside the context of an EAR (when using the JBoss Embeddable EJB3 container), the followingpattern is the one to use:

You will have to experiment to find the right setting for other application servers.

IMPORTANT

Some servers (such as GlassFish) require you to specify JNDI names for all EJBcomponents explicitly. In this case, you can pick your own pattern.

In an EJB3 environment, we recommend the use of a special built-in component for transactionmanagement, that is fully aware of container transactions, and can correctly process transactionsuccess events registered with the Events component. If you do not add this line to your components.xml file, Seam will not know when container-managed transactions end:

<interceptors> <interceptor> <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class> </interceptor></interceptors> <assembly-descriptor> <interceptor-binding> <ejb-name>*</ejb-name> <interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class> </interceptor-binding></assembly-descriptor>

<core:init jndi-name="myEarName/#{ejbName}/local" />

<core:init jndi-name="#{ejbName}/local" />

Seam 2 Reference Guide

310

Page 316: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

26.1.6. The Final Item

There is one final item you need to know about. You must place a seam.properties, META-INF/seam.properties or META-INF/components.xml file in any archive in which your Seamcomponents are deployed (even an empty properties file will do). At startup, Seam will scan anyarchives with seam.properties files for seam components.

In a web archive (WAR) file, you must place a seam.properties file in the WEB-INF/classesdirectory if you have any Seam components included here.

That is why all the Seam examples have an empty seam.properties file and why this file must beincluded for everything to work correctly.

The seam.properties file is the result of a workaround for a limitation of the JVM—if we did not usethis mechanism, our next best option would be to force you to list every component explicitly in components.xml.

26.2. USING ALTERNATE JPA PROVIDERS

Seam comes packaged and configured with Hibernate as the default JPA provider. If you require usinga different JPA provider you must tell seam about it.

NOTE

Configuration of the JPA provider will be easier in the future and will not requireconfiguration changes, unless you are adding a custom persistence providerimplementation.

Telling seam about a different JPA provider can be be done in one of two ways:

Update your application's components.xml so that the generic PersistenceProvider takesprecedence over the hibernate version. Simply add the following to the file:

If you want to take advantage of your JPA provider's non-standard features you will need to write youown implementation of the PersistenceProvider. Use HibernatePersistenceProvider as astarting point. Then you will need to tell seam to use it as before.

All that is left is updating the persistence.xml file with the correct provider class, and what everproperties your provider needs. Your new provider's jar files will need to be packaged in theapplication if they are needed.

<transaction:ejb-transaction/>

<component name="org.jboss.seam.persistence.persistenceProvider" class="org.jboss.seam.persistence.PersistenceProvider" scope="stateless"></component>

<component name="org.jboss.seam.persistence.persistenceProvider" class="org.your.package.YourPersistenceProvider"></component>

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

311

Page 317: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

26.3. CONFIGURING SEAM IN JAVA EE 5

If you are running in a Java EE 5 environment, this is all the configuration required to start using Seam.

26.3.1. Packaging

Once you have packaged all this stuff together into an EAR, the archive structure will look somethinglike this:

my-application.ear/ jboss-seam.jar lib/ jboss-el.jar META-INF/ MANIFEST.MF application.xml my-application.war/ META-INF/ MANIFEST.MF WEB-INF/ web.xml components.xml faces-config.xml lib/ jsf-facelets.jar jboss-seam-ui.jar login.jsp register.jsp ... my-application.jar/ META-INF/ MANIFEST.MF persistence.xml seam.properties org/ jboss/ myapplication/ User.class Login.class LoginBean.class

Seam 2 Reference Guide

312

Page 318: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

You should declare jboss-seam.jar as an ejb module in META-INF/application.xml; jboss-el.jar should be placed in the EAR's lib directory (putting it in the EAR classpath.

If you want to use jBPM or Drools, you must include the needed jars in the EAR's lib directory.

If you want to use facelets (our recommendation), you must include jsf-facelets.jar in the WEB-INF/lib directory of the WAR.

If you want to use the Seam tag library (most Seam applications do), you must include jboss-seam-ui.jar in the WEB-INF/lib directory of the WAR. If you want to use the PDF or email tag libraries,you need to put jboss-seam-pdf.jar or jboss-seam-mail.jar in WEB-INF/lib.

If you want to use the Seam debug page (only works for applications using facelets), you must include jboss-seam-debug.jar in the WEB-INF/lib directory of the WAR.

Seam ships with several example applications that are deployable in any Java EE container thatsupports EJB 3.0.

I really wish that was all there was to say on the topic of configuration but unfortunately we are onlyabout a third of the way there; feel free to skip over the rest of this section and come back to it later.

26.4. CONFIGURING SEAM IN J2EE

Seam is useful even if you are not yet ready to delve into EJB 3.0. In this case you would useHibernate3 or JPA instead of EJB 3.0 persistence, and plain JavaBeans instead of session beans. Youwill miss out on some of the nice features of session beans but it will be very easy to migrate to EJB 3.0when you are ready and, in the meantime, you will be able to take advantage of Seam's uniquedeclarative state management architecture.

Seam JavaBean components do not provide declarative transaction demarcation like session beans do.You could manage your transactions manually using the JTA UserTransaction or decoratively usingSeam's @Transactional annotation. But most applications will just use Seam managed transactionswhen using Hibernate with JavaBeans.

Register.class RegisterBean.class ...

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

313

Page 319: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The Seam distribution includes a version of the booking example application that uses Hibernate3 andJavaBeans instead of EJB3, and another version that uses JPA and JavaBeans. These exampleapplications are ready to deploy into any J2EE application server.

26.4.1. Boostrapping Hibernate in Seam

Seam will bootstrap a Hibernate SessionFactory from your hibernate.cfg.xml file if you install abuilt-in component:

You will also need to configure a managed session if you want a Seam managed Hibernate Session tobe available via injection.

26.4.2. Boostrapping JPA in Seam

Seam will bootstrap a JPA EntityManagerFactory from your persistence.xml file if you installthis built-in component:

You will also need to configure a managed persistence context if you want a Seam managed JPA EntityManager to be available via injection.

26.4.3. Packaging

We can package our application as a WAR, in the following structure:

<persistence:hibernate-session-factory name="hibernateSessionFactory"/>

<persistence:managed-hibernate-session name="hibernateSession" session-factory="#{hibernateSessionFactory}"/>

<persistence:entity-manager-factory name="entityManagerFactory"/>

<persistence:managed-persistence-context name="entityManager" entity-manager-factory="#{entityManagerFactory}"/>

my-application.war/ META-INF/ MANIFEST.MF WEB-INF/ web.xml components.xml faces-config.xml lib/ jboss-seam.jar jboss-seam-ui.jar jboss-el.jar jsf-facelets.jar hibernate3.jar hibernate-annotations.jar hibernate-validator.jar ... my-application.jar/

Seam 2 Reference Guide

314

Page 320: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

If we want to deploy Hibernate in a non-EE environment like Tomcat or TestNG, we need to do a littlebit more work.

26.5. CONFIGURING SEAM IN JAVA SE, WITHOUT JBOSS EMBEDDED

It is possible to use Seam completely outside of an EE environment. In this case, you need to tell Seamhow to manage transactions, since there will be no JTA available. If you are using JPA, you can tellSeam to use JPA resource-local transactions for instance. EntityTransaction, like so:

If you are using Hibernate, you can tell Seam to use the Hibernate transaction API like this:

You will also need to define a datasource.

26.6. CONFIGURING JBPM IN SEAM

Seam's jBPM integration is not installed by default, so you will need to enable jBPM by installing abuilt-in component. You will also need to explicitly list your process and pageflow definitions. In components.xml:

No further special configuration is needed if you only have pageflows. If you do have business processdefinitions, you need to provide a jBPM configuration, and a Hibernate configuration for jBPM. TheSeam DVD Store demo includes example jbpm.cfg.xml and hibernate.cfg.xml files that willwork with Seam:

META-INF/ MANIFEST.MF seam.properties hibernate.cfg.xml org/ jboss/ myapplication/ User.class Login.class Register.class ... login.jsp register.jsp ...

<transaction:entity-transaction entity-manager="#{entityManager}"/>

<transaction:hibernate-transaction session="#{session}"/>

<bpm:jbpm> <bpm:pageflow-definitions> <value>createDocument.jpdl.xml</value> <value>editDocument.jpdl.xml</value> <value>approveDocument.jpdl.xml</value> </bpm:pageflow-definitions> <bpm:process-definitions> <value>documentLifecycle.jpdl.xml</value> </bpm:process-definitions></bpm:jbpm>

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

315

Page 321: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The most important thing to notice here is that jBPM transaction control is disabled. Seam or EJB3should control the JTA transactions.

26.6.1. Packaging

There is not yet any well-defined packaging format for jBPM configuration and process/pageflowdefinition files. In the Seam examples we have decided to package all these files into the root of theEAR. In future, we will probably design some other standard packaging format. So the EAR lookssomething like this:

<jbpm-configuration>

<jbpm-context> <service name="persistence"> <factory> <bean class="org.jbpm.persistence.db.DbPersistenceServiceFactory"> <field name="isTransactionEnabled"><false/></field> </bean> </factory> </service> <service name="tx" factory="org.jbpm.tx.TxServiceFactory" /> <service name="message" factory="org.jbpm.msg.db.DbMessageServiceFactory" /> <service name="scheduler" factory="org.jbpm.scheduler.db.DbSchedulerServiceFactory" /> <service name="logging" factory="org.jbpm.logging.db.DbLoggingServiceFactory" /> <service name="authentication" factory="org.jbpm.security.authentication.DefaultAuthenticationServiceFactory" /> </jbpm-context>

</jbpm-configuration>

my-application.ear/ jboss-seam.jar lib/ jboss-el.jar jbpm-3.1.jar META-INF/ MANIFEST.MF application.xml my-application.war/ META-INF/ MANIFEST.MF WEB-INF/ web.xml components.xml faces-config.xml lib/ jsf-facelets.jar jboss-seam-ui.jar login.jsp

Seam 2 Reference Guide

316

Page 322: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

26.7. CONFIGURING SFSB AND SESSION TIMEOUTS IN JBOSS AS

It is very important that the timeout for Stateful Session Beans is set higher than the timeout for HTTPSessions, otherwise SFSB's may time out before the user's HTTP session has ended. JBoss ApplicationServer has a default session bean timeout of 30 minutes, which is configured in server/default/conf/standardjboss.xml (replace default with your own configuration).

The default SFSB timeout can be adjusted by modifying the value of max-bean-life in the LRUStatefulContextCachePolicy cache configuration:

register.jsp ... my-application.jar/ META-INF/ MANIFEST.MF persistence.xml seam.properties org/ jboss/ myapplication/ User.class Login.class LoginBean.class Register.class RegisterBean.class ... jbpm.cfg.xml hibernate.cfg.xml createDocument.jpdl.xml editDocument.jpdl.xml approveDocument.jpdl.xml documentLifecycle.jpdl.xml

<container-cache-conf> <cache-policy>org.jboss.ejb.plugins.LRUStatefulContextCachePolicy</cache-policy> <cache-policy-conf> <min-capacity>50</min-capacity> <max-capacity>1000000</max-capacity> <remover-period>1800</remover-period>

<!-- SFSB timeout in seconds; 1800 seconds == 30 minutes --> <max-bean-life>1800</max-bean-life>

<overager-period>300</overager-period> <max-bean-age>600</max-bean-age> <resizer-period>400</resizer-period> <max-cache-miss-period>60</max-cache-miss-period> <min-cache-miss-period>1</min-cache-miss-period> <cache-load-factor>0.75</cache-load-factor> </cache-policy-conf></container-cache-conf>

CHAPTER 26. CONFIGURING SEAM AND PACKAGING SEAM APPLICATIONS

317

Page 323: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The default HTTP session timeout can be modified in server/<profile>/deploy/jboss-web.deployer/conf/web.xml for JBoss EAP 4.3. The following entry in this file controls the defaultsession timeout for all web applications:

To override this value for your own application, simply include this entry in your application's own web.xml.

26.8. RUNNING SEAM IN A PORTLET

If you want to run your Seam application in a portlet, take a look at the JBoss Portlet Bridge, animplementation of JSR-301 that supports JSF within a portlet, with extensions for Seam andRichFaces. See http://labs.jboss.com/portletbridge for more.

NOTE

Seam Integration with JBoss Portlet Bridge is marked as technology preview, sostandard support is not guaranteed.

<session-config> <!-- HTTP Session timeout, in minutes --> <session-timeout>30</session-timeout></session-config>

Seam 2 Reference Guide

318

Page 324: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 27. SEAM ANNOTATIONSWhen you write a Seam application, you will use a lot of annotations. Seam lets you use annotations toachieve a declarative style of programming. Most of the annotations you will use are defined by theEJB 3.0 specification. The annotations for data validation are defined by the Hibernate Validatorpackage. Finally, Seam defines its own set of annotations, which we will describe in this chapter.

All of these annotations are defined in the package org.jboss.seam.annotations.

27.1. ANNOTATIONS FOR COMPONENT DEFINITION

The first group of annotations lets you define a Seam component. These annotations appear on thecomponent class.

@Name

Defines the Seam component name for a class. This annotation is required for all Seam components.

@Scope

Defines the default context of the component. The possible values are defined by the ScopeTypeenumeration: EVENT, PAGE, CONVERSATION, SESSION, BUSINESS_PROCESS, APPLICATION, STATELESS.

When no scope is explicitly specified, the default depends upon the component type. For statelesssession beans, the default is STATELESS. For entity beans and stateful session beans, the default is CONVERSATION. For JavaBeans, the default is EVENT.

@Role

Allows a Seam component to be bound to multiple contexts variables. The @Name/@Scopeannotations define a "default role". Each @Role annotation defines an additional role.

name — the context variable name.

scope — the context variable scope. When no scope is explicitly specified, the defaultdepends upon the component type, as above.

@Roles

Allows specification of multiple additional roles.

@Name("componentName")

@Scope(ScopeType.CONVERSATION)

@Role(name="roleName", scope=ScopeType.SESSION)

@Roles({ @Role(name="user", scope=ScopeType.CONVERSATION), @Role(name="currentUser", scope=ScopeType.SESSION) })

CHAPTER 27. SEAM ANNOTATIONS

319

Page 325: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

@BypassInterceptors

Disables Seam all interceptors on a particular component or method of a component.

@JndiName

Specifies the JNDI name that Seam will use to look up the EJB component. If no JNDI name isexplicitly specified, Seam will use the JNDI pattern specified by org.jboss.seam.core.init.jndiPattern.

@Conversational

Specifies that a conversation scope component is conversational, meaning that no method of thecomponent may be called unless a long-running conversation is active.

@PerNestedConversation

Limits the scope of a CONVERSATION-scoped component to just the parent conversation in whichit was instantiated. The component instance will not be visible to nested child conversations, whichwill get their own instance.

WARNING

This implies that a component will be visible for some part of a request cycle,and invisible after that. It is not recommended that applications use thisfeature.

@Startup

Specifies that an application scope component is started immediately at initialization time. This ismainly used for certain built-in components that bootstrap critical infrastructure such as JNDI,datasources, etc.

Specifies that a session scope component is started immediately at session creation time.

@BypassInterceptors

@JndiName("my/jndi/name")

@Conversational

@PerNestedConversation

@Scope(APPLICATION) @Startup(depends="org.jboss.seam.bpm.jbpm")

@Scope(SESSION) @Startup

Seam 2 Reference Guide

320

Page 326: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

depends — specifies that the named components must be started first, if they are installed.

@Install

Specifies whether or not a component should be installed by default. The lack of an @Installannotation indicates a component should be installed.

Specifies that a component should only be stalled if the components listed as dependencies arealso installed.

Specifies that a component should only be installed if a component that is implemented by a certainclass is installed. This is useful when the dependency doesn't have a single well-known name.

Specifies that a component should only be installed if the named class is in the classpath.

Specifies the precedence of the component. If multiple components with the same name exist, theone with the higher precedence will be installed. The defined precedence values are (in ascendingorder):

BUILT_IN — Precedence of all built-in Seam components

FRAMEWORK — Precedence to use for components of frameworks which extend Seam

APPLICATION — Order of application components (the default precedence)

DEPLOYMENT — Precedence to use for components which override application componentsin a particular deployment

MOCK — Precedence for mock objects used in testing

@Synchronized

Specifies that a component is accessed concurrently by multiple clients, and that Seam shouldserialize requests. If a request is not able to obtain its lock on the component in the given timeoutperiod, an exception will be raised.

@ReadOnly

@Install(false)

@Install(dependencies="org.jboss.seam.bpm.jbpm")

@Install(genericDependencies=ManagedQueueSender.class)

@Install(classDependencies="org.hibernate.Session")

@Install(precedence=BUILT_IN)

@Synchronized(timeout=1000)

@ReadOnly

CHAPTER 27. SEAM ANNOTATIONS

321

Page 327: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Specifies that a JavaBean component or component method does not require state replication atthe end of the invocation.

@AutoCreate

Specifies that a component will be automatically created, even if the client does not specify create=true.

27.2. ANNOTATIONS FOR BIJECTION

The next two annotations control bijection. These attributes occur on component instance variables orproperty accessor methods.

@In

Specifies that a component attribute is to be injected from a context variable at the beginning ofeach component invocation. If the context variable is null, an exception will be thrown.

Specifies that a component attribute is to be injected from a context variable at the beginning ofeach component invocation. The context variable may be null.

Specifies that a component attribute is to be injected from a context variable at the beginning ofeach component invocation. If the context variable is null, an instance of the component isinstantiated by Seam.

Specifies the name of the context variable explicitly, instead of using the annotated instancevariable name.

Specifies that a component attribute is to be injected by evaluating a JSF EL expression at thebeginning of each component invocation.

value — specifies the name of the context variable. Default to the name of the componentattribute. Alternatively, specifies a JSF EL expression, surrounded by #{...}.

create — specifies that Seam should instantiate the component with the same name as thecontext variable if the context variable is undefined (null) in all contexts. Default to false.

required — specifies Seam should throw an exception if the context variable is undefinedin all contexts.

@AutoCreate

@In

@In(required=false)

@In(create=true)

@In(value="contextVariableName")

@In(value="#{customer.addresses['shipping']}")

Seam 2 Reference Guide

322

Page 328: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

@Out

Specifies that a component attribute that is a Seam component is to be passed to its contextvariable at the end of the invocation. If the attribute is null, an exception is thrown.

Specifies that a component attribute that is a Seam component is to be passed to its contextvariable at the end of the invocation. The attribute may be null.

Specifies that a component attribute that is not a Seam component type is to be passed to aspecific scope at the end of the invocation.

Alternatively, if no scope is explicitly specified, the scope of the component with the @Out attributeis used (or the EVENT scope if the component is stateless).

Specifies the name of the context variable explicitly, instead of using the annotated instancevariable name.

value — specifies the name of the context variable. Default to the name of the componentattribute.

required — specifies Seam should throw an exception if the component attribute is nullduring the transfer of information.

It is quite common for these annotations to occur together, for example:

The next annotation supports the manager component pattern, where a Seam component that managesthe lifecycle of an instance of some other class that is to be injected. It appears on a component gettermethod.

@Unwrap

Specifies that the object returned by the annotated getter method is the thing that is injectedinstead of the component instance itself.

The next annotation supports the factory component pattern, where a Seam component is responsiblefor initializing the value of a context variable. This is especially useful for initializing any state neededfor rendering the response to a non-faces request. It appears on a component method.

@Factory

@Out

@Out(required=false)

@Out(scope=ScopeType.SESSION)

@Out(value="contextVariableName")

@In(create=true) @Out private User currentUser;

@Unwrap

CHAPTER 27. SEAM ANNOTATIONS

323

Page 329: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Specifies that the method of the component is used to initialize the value of the named contextvariable, when the context variable has no value. This style is used with methods that return void.

Specifies that the method returns a value that Seam should use to initialize the value of the namedcontext variable, when the context variable has no value. This style is used with methods thatreturn a value. If no scope is explicitly specified, the scope of the component with the @Factorymethod is used (unless the component is stateless, in which case the EVENT context is used).

value — specifies the name of the context variable. If the method is a getter method,default to the JavaBeans property name.

scope — specifies the scope that Seam should bind the returned value to. Only meaningfulfor factory methods which return a value.

autoCreate — specifies that this factory method should be automatically called wheneverthe variable is asked for, even if @In does not specify create=true.

This annotation lets you inject a Log:

@Logger

Specifies that a component field is to be injected with an instance of org.jboss.seam.log.Log.For entity beans, the field must be declared as static.

value — specifies the name of the log category. Default to the name of the componentclass.

The last annotation lets you inject a request parameter value:

@RequestParameter

Specifies that a component attribute is to be injected with the value of a request parameter. Basictype conversions are performed automatically.

value — specifies the name of the request parameter. Default to the name of thecomponent attribute.

27.3. ANNOTATIONS FOR COMPONENT LIFECYCLE METHODS

These annotations allow a component to react to its own lifecycle events. They occur on methods ofthe component. There may be only one of each per component class.

@Factory("processInstance") public void createProcessInstance() { ... }

@Factory("processInstance", scope=CONVERSATION) public ProcessInstance createProcessInstance() { ... }

@Logger("categoryName")

@RequestParameter("parameterName")

Seam 2 Reference Guide

324

Page 330: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

@Create

Specifies that the method should be called when an instance of the component is instantiated bySeam. Note that create methods are only supported for JavaBeans and stateful session beans.

@Destroy

Specifies that the method should be called when the context ends and its context variables aredestroyed. Note that destroy methods are only supported for JavaBeans and stateful sessionbeans.

Destroy methods should be used only for cleanup. Seam catches, logs and swallows any exception thatpropagates out of a destroy method.

@Observer

Specifies that the method should be called when a component-driven event of the specified typeoccurs.

Specifies that the method should be called when an event of the specified type occurs but that aninstance should not be created if one doesn't exist. If an instance does not exist and create is false,the event will not be observed. The default value for create is true.

27.4. ANNOTATIONS FOR CONTEXT DEMARCATION

These annotations provide declarative conversation demarcation. They appear on methods of Seamcomponents, usually action listener methods.

Every web request has a conversation context associated with it. Most of these conversations end atthe end of the request. If you want a conversation that span multiple requests, you must "promote" thecurrent conversation to a long-running conversation by calling a method marked with @Begin.

@Begin

Specifies that a long-running conversation begins when this method returns a non-null outcomewithout exception.

Specifies that if a long-running conversation is already in progress, the conversation context issimply propagated.

@Create

@Destroy

@Observer("somethingChanged")

@Observer(value="somethingChanged",create=false)

@Begin

@Begin(join=true)

CHAPTER 27. SEAM ANNOTATIONS

325

Page 331: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Specifies that if a long-running conversation is already in progress, a new nested conversationcontext begins. The nested conversation will end when the next @End is encountered, and the outerconversation will resume. It is perfectly legal for multiple nested conversations to existconcurrently in the same outer conversation.

Specifies a jBPM process definition name that defines the pageflow for this conversation.

Specify the flush mode of any Seam-managed persistence contexts. flushMode=FlushModeType.MANUAL supports the use of atomic conversations where all writeoperations are queued in the conversation context until an explicit call to flush() (which usuallyoccurs at the end of the conversation).

join — determines the behavior when a long-running conversation is already in progress. If true, the context is propagated. If false, an exception is thrown. Default to false. Thissetting is ignored when nested=true is specified.

nested — specifies that a nested conversation should be started if a long-runningconversation is already in progress.

flushMode — set the flush mode of any Seam-managed Hibernate sessions or JPApersistence contexts that are created during this conversation.

pageflow — a process definition name of a jBPM process definition deployed via org.jboss.seam.bpm.jbpm.pageflowDefinitions.

@End

Specifies that a long-running conversation ends when this method returns a non-null outcomewithout exception.

beforeRedirect — by default, the conversation will not actually be destroyed until afterany redirect has occurred. Setting beforeRedirect=true specifies that the conversationshould be destroyed at the end of the current request, and that the redirect will beprocessed in a new temporary conversation context.

@StartTask

Starts a jBPM task. Specifies that a long-running conversation begins when this method returns anon-null outcome without exception. This conversation is associated with the jBPM task specified inthe named request parameter. Within the context of this conversation, a business process contextis also defined, for the business process instance of the task instance.

The jBPM TaskInstance will be available in a request context variable named

@Begin(nested=true)

@Begin(pageflow="process definition name")

@Begin(flushMode=FlushModeType.MANUAL)

@End

@StartTask

Seam 2 Reference Guide

326

Page 332: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

taskInstance. The jPBM ProcessInstance will be available in a request contextvariable named processInstance. (Of course, these objects are available for injection via@In.)

taskIdParameter — the name of a request parameter which holds the id of the task.Default to "taskId", which is also the default used by the Seam taskList JSFcomponent.

flushMode — set the flush mode of any Seam-managed Hibernate sessions or JPApersistence contexts that are created during this conversation.

@BeginTask

Resumes work on an incomplete jBPM task. Specifies that a long-running conversation begins whenthis method returns a non-null outcome without exception. This conversation is associated with thejBPM task specified in the named request parameter. Within the context of this conversation, abusiness process context is also defined, for the business process instance of the task instance.

The jBPM org.jbpm.taskmgmt.exe.TaskInstance will be available in a requestcontext variable named taskInstance. The jPBM org.jbpm.graph.exe.ProcessInstance will be available in a request context variablenamed processInstance.

taskIdParameter — the name of a request parameter which holds the id of the task.Default to "taskId", which is also the default used by the Seam taskList JSFcomponent.

flushMode — set the flush mode of any Seam-managed Hibernate sessions or JPApersistence contexts that are created during this conversation.

@EndTask

Ends a jBPM task. Specifies that a long-running conversation ends when this method returns a non-null outcome, and that the current task is complete. Triggers a jBPM transition. The actualtransition triggered will be the default transition unless the application has called Transition.setName() on the built-in component named transition.

Triggers the given jBPM transition.

transition — the name of the jBPM transition to be triggered when ending the task.Defaults to the default transition.

beforeRedirect — by default, the conversation will not actually be destroyed until afterany redirect has occurred. Setting beforeRedirect=true specifies that the conversationshould be destroyed at the end of the current request, and that the redirect will beprocessed in a new temporary conversation context.

@CreateProcess

@BeginTask

@EndTask

@EndTask(transition="transitionName")

CHAPTER 27. SEAM ANNOTATIONS

327

Page 333: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Creates a new jBPM process instance when the method returns a non-null outcome withoutexception. The ProcessInstance object will be available in a context variable named processInstance.

definition — the name of the jBPM process definition deployed via org.jboss.seam.bpm.jbpm.processDefinitions.

@ResumeProcess

Re-enters the scope of an existing jBPM process instance when the method returns a non-nulloutcome without exception. The ProcessInstance object will be available in a context variablenamed processInstance.

processIdParameter — the name a request parameter holding the process id. Default to "processId".

@Transition

Marks a method as signalling a transition in the current jBPM process instance whenever themethod returns a non-null result.

27.5. ANNOTATIONS FOR USE WITH SEAM JAVABEAN COMPONENTSIN A J2EE ENVIRONMENT

Seam provides an annotation that lets you force a rollback of the JTA transaction for certain actionlistener outcomes.

@Transactional

Specifies that a JavaBean component should have a similar transactional behavior to the defaultbehavior of a session bean component. ie. method invocations should take place in a transaction,and if no transaction exists when the method is called, a transaction will be started just for thatmethod. This annotation may be applied at either class or method level.

Do not use this annotation on EJB 3.0 components, use @TransactionAttribute!

@ApplicationException

@CreateProcess(definition="process definition name")

@ResumeProcess(processIdParameter="processId")

@Transition("cancel")

@Transactional

@ApplicationException

Seam 2 Reference Guide

328

Page 334: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Synonym for javax.ejb.ApplicationException, for use in a pre -Java EE 5 environment. Applied to anexception to denote that it is an application exception and should be reported to the clientdirectly(for instance, unwrapped).

Do not use this annotation on EJB 3.0 components, use @javax.ejb.ApplicationExceptioninstead.

rollback — by default false, if true this exception should set the transaction to rollbackonly

end — by default false, if true this exception should end the current long-runningconversation

@Interceptors

Synonym for javax.interceptors.Interceptors, for use in a pre-Java EE 5 environment. Note that thismay only be used as a meta-annotation. Declares an ordered list of interceptors for a class ormethod.

Do not use this annotations on EJB 3.0 components, use @javax.interceptor.Interceptorsinstead.

These annotations are mostly useful for JavaBean Seam components. If you use EJB 3.0 components,you should use the standard Java EE5 annotation.

27.6. ANNOTATIONS FOR EXCEPTIONS

These annotations let you specify how Seam should handle an exception that propagates out of a Seamcomponent.

@Redirect

Specifies that the annotated exception causes a browser redirect to a specified view id.

viewId — specifies the JSF view id to redirect to. You can use EL here.

message — a message to be displayed, default to the exception message.

end — specifies that the long-running conversation should end, default to false.

@HttpError

Specifies that the annotated exception causes a HTTP error to be sent.

errorCode — the HTTP error code, default to 500.

message — a message to be sent with the HTTP error, default to the exception message.

@Interceptors({DVDInterceptor, CDInterceptor})

@Redirect(viewId="error.jsp")

@HttpError(errorCode=404)

CHAPTER 27. SEAM ANNOTATIONS

329

Page 335: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

end — specifies that the long-running conversation should end, default to false.

27.7. ANNOTATIONS FOR SEAM REMOTING

Seam Remoting requires that the local interface of a session bean be annotated with the followingannotation:

@WebRemote

Indicates that the annotated method may be called from client-side JavaScript. The excludeproperty is optional and allows objects to be excluded from the result's object graph (see theRemoting chapter for more details).

27.8. ANNOTATIONS FOR SEAM INTERCEPTORS

The following annotations appear on Seam interceptor classes.

Please refer to the documentation for the EJB 3.0 specification for information about the annotationsrequired for EJB interceptor definition.

@Interceptor

Specifies that this interceptor is stateless and Seam may optimize replication.

Specifies that this interceptor is a "client-side" interceptor that is called before the EJB container.

Specifies that this interceptor is positioned higher in the stack than the given interceptors.

Specifies that this interceptor is positioned deeper in the stack than the given interceptors.

27.9. ANNOTATIONS FOR ASYNCHRONOUSLY

The following annotations are used to declare an asynchronous method, for example:

@WebRemote(exclude="path.to.exclude")

@Interceptor(stateless=true)

@Interceptor(type=CLIENT)

@Interceptor(around={SomeInterceptor.class, OtherInterceptor.class})

@Interceptor(within={SomeInterceptor.class, OtherInterceptor.class})

@Asynchronous public void scheduleAlert(Alert alert, @Expiration Date date) { ... }

Seam 2 Reference Guide

330

Page 336: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

@Asynchronous

Specifies that the method call is processed asynchronously.

@Duration

Specifies that a parameter of the asynchronous call is the duration before the call is processed (orfirst processed for recurring calls).

@Expiration

Specifies that a parameter of the asynchronous call is the datetime at which the call is processed(or first processed for recurring calls).

@IntervalDuration

Specifies that an asynchronous method call recurs, and that the annotated parameter is durationbetween recurrences.

27.10. ANNOTATIONS FOR USE WITH JSF

The following annotations make working with JSF easier.

@Converter

Allows a Seam component to act as a JSF converter. The annotated class must be a Seamcomponent, and must implement javax.faces.convert.Converter.

id — the JSF converter id. Defaults to the component name.

forClass — if specified, register this component as the default converter for a type.

@Validator

Allows a Seam component to act as a JSF validator. The annotated class must be a Seamcomponent, and must implement javax.faces.validator.Validator.

id — the JSF validator id. Defaults to the component name.

@Asynchronous public Timer scheduleAlerts(Alert alert, @Expiration Date date, @IntervalDuration long interval) { ... }

@Asynchronous

@Duration

@Expiration

@IntervalDuration

CHAPTER 27. SEAM ANNOTATIONS

331

Page 337: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

27.10.1. Annotations for use with dataTable

The following annotations make it easy to implement clickable lists backed by a stateful session bean.They appear on attributes.

@DataModel

Returns a property of type List, Map, Set or Object[] as a JSF DataModel into the scope of theowning component (or the EVENT scope if the owning component is STATELESS). In the case of Map, each row of the DataModel is a Map.Entry.

value — name of the conversation context variable. Default to the attribute name.

scope — if scope=ScopeType.PAGE is explicitly specified, the DataModel will be kept inthe PAGE context.

@DataModelSelection

Injects the selected value from the JSF DataModel (this is the element of the underlyingcollection, or the map value). If only one @DataModel attribute is defined for a component, theselected value from that DataModel will be injected. Otherwise, the component name of each @DataModel must be specified in the value attribute for each @DataModelSelection.

If PAGE scope is specified on the associated @DataModel, then, in addition to the DataModelSelection being injected, the associated DataModel will also be injected. In this case, if the propertyannotated with @DataModel is a getter method, then a setter method for the property must also bepart of the Business API of the containing Seam Component.

value — name of the conversation context variable. Not needed if there is exactly one @DataModel in the component.

@DataModelSelectionIndex

Exposes the selection index of the JSF DataModel as an attribute of the component (this is therow number of the underlying collection, or the map key). If only one @DataModel attribute isdefined for a component, the selected value from that DataModel will be injected. Otherwise, thecomponent name of each @DataModel must be specified in the value attribute for each @DataModelSelectionIndex.

value — name of the conversation context variable. Not needed if there is exactly one @DataModel in the component.

27.11. META-ANNOTATIONS FOR DATABINDING

These meta-annotations make it possible to implement similar functionality to @DataModel and @DataModelSelection for other datastructures apart from lists.

@DataModel("variableName")

@DataModelSelection

@DataModelSelectionIndex

Seam 2 Reference Guide

332

Page 338: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

@DataBinderClass

Specifies that an annotation is a databinding annotation.

@DataSelectorClass

Specifies that an annotation is a dataselection annotation.

27.12. ANNOTATIONS FOR PACKAGING

This annotation provides a mechanism for declaring information about a set of components that arepackaged together. It can be applied to any Java package.

@Namespace

Specifies that components in the current package are associated with the given namespace. Thedeclared namespace can be used as an XML namespace in a components.xml file to simplifyapplication configuration.

Specifies a namespace to associate with a given package. Additionally, it specifies a componentname prefix to be applied to component names specified in the XML file. For example, an XMLelement named init that is associated with this namespace would be understood to actually referto a component named org.jboss.seam.core.init.

27.13. ANNOTATIONS FOR INTEGRATING WITH THE SERVLETCONTAINER

These annotations allow you to integrate your Seam components with the servlet container.

@Filter

Use the Seam component (which implements javax.servlet.Filter) annotated with @Filteras a servlet filter. It will be executed by Seam's master filter.

Specifies that this filter is positioned higher in the stack than the given filters.

Specifies that this filter is positioned deeper in the stack than the given filters.

@DataBinderClass(DataModelBinder.class)

@DataSelectorClass(DataModelSelector.class)

@Namespace(value="http://jboss.com/products/seam/example/seampay")

@Namespace(value="http://jboss.com/products/seam/core", prefix="org.jboss.seam.core")

@Filter(around={"seamComponent", "otherSeamComponent"})

@Filter(within={"seamComponent", "otherSeamComponent"})

CHAPTER 27. SEAM ANNOTATIONS

333

Page 339: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 28. BUILT-IN SEAM COMPONENTSThis chapter describes Seam's built in components, and their configuration properties. The built incomponents will be created even if they are not listed in your components.xml file, but if you need tooverride default properties or specify more than one component of a certain type, components.xml isused.

You can replace any of the built in components with your own implementations simply by specifyingthe name of one of the built in components on your own class using @Name.

Even though all the built in components use a qualified name, most of them are aliased to unqualifiednames by default. These aliases specify auto-create="true", so you do not need to use create=true when injecting built-in components by their unqualified name.

28.1. CONTEXT INJECTION COMPONENTS

The first set of built in components exist purely to support injection of various contextual objects. Forexample, the following component instance variable would have the Seam session context objectinjected:

org.jboss.seam.core.contexts

Component that provides access to Seam Context objects, for example org.jboss.seam.core.contexts.sessionContext['user'].

org.jboss.seam.faces.facesContext

Manager component for the FacesContext context object (not a true Seam context)

All of these components are always installed.

28.2. UTILITY COMPONENTS

These components are merely useful.

org.jboss.seam.faces.facesMessages

Allows faces success messages to propagate across a browser redirect.

add(FacesMessage facesMessage) — add a faces message, which will be displayedduring the next render response phase that occurs in the current conversation.

add(String messageTemplate) — add a faces message, rendered from the givenmessage template which may contain EL expressions.

add(Severity severity, String messageTemplate) — add a faces message,rendered from the given message template which may contain EL expressions.

addFromResourceBundle(String key) — add a faces message, rendered from amessage template defined in the Seam resource bundle which may contain EL expressions.

@In private Context sessionContext;

Seam 2 Reference Guide

334

Page 340: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

addFromResourceBundle(Severity severity, String key) — add a facesmessage, rendered from a message template defined in the Seam resource bundle whichmay contain EL expressions.

clear() — clear all messages.

org.jboss.seam.faces.redirect

A convenient API for performing redirects with parameters (this is especially useful forbookmarkable search results screens).

redirect.viewId — the JSF view id to redirect to.

redirect.conversationPropagationEnabled — determines whether theconversation will propagate across the redirect.

redirect.parameters — a map of request parameter name to value, to be passed in theredirect request.

execute() — perform the redirect immediately.

captureCurrentRequest() — stores the view id and request parameters of the currentGET request (in the conversation context), for later use by calling execute().

org.jboss.seam.faces.httpError

A convenient API for sending HTTP errors.

org.jboss.seam.core.events

An API for raising events that can be observed via @Observer methods, or method bindings in components.xml.

raiseEvent(String type) — raise an event of a particular type and distribute to allobservers.

raiseAsynchronousEvent(String type) — raise an event to be processedasynchronously by the EJB3 timer service.

raiseTimedEvent(String type, ....) — schedule an event to be processedasynchronously by the EJB3 timer service.

addListener(String type, String methodBinding) — add an observer for aparticular event type.

org.jboss.seam.core.interpolator

An API for interpolating the values of JSF EL expressions in Strings.

interpolate(String template) — scan the template for JSF EL expressions of theform #{...} and replace them with their evaluated values.

org.jboss.seam.core.expressions

An API for creating value and method bindings.

createValueBinding(String expression) — create a value binding object.

CHAPTER 28. BUILT-IN SEAM COMPONENTS

335

Page 341: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

createMethodBinding(String expression) — create a method binding object.

org.jboss.seam.core.pojoCache

Manager component for a JBoss Cache PojoCache instance.

pojoCache.cfgResourceName — the name of the configuration file. Default to treecache.xml.

All of these components are always installed.

28.3. COMPONENTS FOR INTERNATIONALIZATION AND THEMES

The next group of components make it easy to build internationalized user interfaces using Seam.

org.jboss.seam.core.locale

The Seam locale.

org.jboss.seam.international.timezone

The Seam timezone. The timezone is session scoped.

org.jboss.seam.core.resourceBundle

The Seam resource bundle. The resource bundle is stateless. The Seam resource bundle performs adepth-first search for keys in a list of Java resource bundles.

org.jboss.seam.core.resourceLoader

The resource loader provides access to application resources and resource bundles.

resourceLoader.bundleNames — the names of the Java resource bundles to searchwhen the Seam resource bundle is used. Default to messages.

org.jboss.seam.international.localeSelector

Supports selection of the locale either at configuration time, or by the user at runtime.

select() — select the specified locale.

localeSelector.locale — the actual java.util.Locale.

localeSelector.localeString — the string representation of the locale.

localeSelector.language — the language for the specified locale.

localeSelector.country — the country for the specified locale.

localeSelector.variant — the variant for the specified locale.

localeSelector.supportedLocales — a list of SelectItems representing thesupported locales listed in jsf-config.xml.

localeSelector.cookieEnabled — specifies that the locale selection should bepersisted via a cookie.

Seam 2 Reference Guide

336

Page 342: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

org.jboss.seam.international.timezoneSelector

Supports selection of the timezone either at configuration time, or by the user at runtime.

select() — select the specified locale.

timezoneSelector.timezone — the actual java.util.TimeZone.

timezoneSelector.timeZoneId — the string representation of the timezone.

timezoneSelector.cookieEnabled — specifies that the timezone selection should bepersisted via a cookie.

org.jboss.seam.international.messages

A map containing internationalized messages rendered from message templates defined in theSeam resource bundle.

org.jboss.seam.theme.themeSelector

Supports selection of the theme either at configuration time, or by the user at runtime.

select() — select the specified theme.

theme.availableThemes — the list of defined themes.

themeSelector.theme — the selected theme.

themeSelector.themes — a list of SelectItems representing the defined themes.

themeSelector.cookieEnabled — specifies that the theme selection should bepersisted via a cookie.

org.jboss.seam.theme.theme

A map containing theme entries.

All of these components are always installed.

28.4. COMPONENTS FOR CONTROLLING CONVERSATIONS

The next group of components allow control of conversations by the application or user interface.

org.jboss.seam.core.conversation

API for application control of attributes of the current Seam conversation.

getId() — returns the current conversation id

isNested() — is the current conversation a nested conversation?

isLongRunning() — is the current conversation a long-running conversation?

getId() — returns the current conversation id

getParentId() — returns the conversation id of the parent conversation

CHAPTER 28. BUILT-IN SEAM COMPONENTS

337

Page 343: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

getRootId() — returns the conversation id of the root conversation

setTimeout(int timeout) — sets the timeout for the current conversation

setViewId(String outcome) — sets the view id to be used when switching back to thecurrent conversation from the conversation switcher, conversation list, or breadcrumbs.

setDescription(String description) — sets the description of the currentconversation to be displayed in the conversation switcher, conversation list, orbreadcrumbs.

redirect() — redirect to the last well-defined view id for this conversation (useful afterlogin challenges).

leave() — exit the scope of this conversation, without actually ending the conversation.

begin() — begin a long-running conversation (equivalent to @Begin).

beginPageflow(String pageflowName) — begin a long-running conversation with apageflow (equivalent to @Begin(pageflow="...")).

end() — end a long-running conversation (equivalent to @End).

pop() — pop the conversation stack, returning to the parent conversation.

root() — return to the root conversation of the conversation stack.

changeFlushMode(FlushModeType flushMode) — change the flush mode of theconversation.

org.jboss.seam.core.conversationList

Manager component for the conversation list.

org.jboss.seam.core.conversationStack

Manager component for the conversation stack (breadcrumbs).

org.jboss.seam.faces.switcher

The conversation switcher.

All of these components are always installed.

28.5. JBPM-RELATED COMPONENTS

These components are for use with jBPM.

org.jboss.seam.pageflow.pageflow

API control of Seam pageflows.

isInProcess() — returns true if there is currently a pageflow in process

getProcessInstance() — returns jBPM ProcessInstance for the current pageflow

Seam 2 Reference Guide

338

Page 344: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

begin(String pageflowName) — begin a pageflow in the context of the currentconversation

reposition(String nodeName) — reposition the current pageflow to a particular node

org.jboss.seam.bpm.actor

API for application control of attributes of the jBPM actor associated with the current session.

setId(String actorId) — sets the jBPM actor id of the current user.

getGroupActorIds() — returns a Set to which jBPM actor ids for the current usersgroups may be added.

org.jboss.seam.bpm.transition

API for application control of the jBPM transition for the current task.

setName(String transitionName) — sets the jBPM transition name to be used whenthe current task is ended via @EndTask.

org.jboss.seam.bpm.businessProcess

API for programmatic control of the association between the conversation and business process.

businessProcess.taskId — the id of the task associated with the current conversation.

businessProcess.processId — the id of the process associated with the currentconversation.

businessProcess.hasCurrentTask() — is a task instance associated with the currentconversation?

businessProcess.hasCurrentProcess() — is a process instance associated with thecurrent conversation.

createProcess(String name) — create an instance of the named process definitionand associate it with the current conversation.

startTask() — start the task associated with the current conversation.

endTask(String transitionName) — end the task associated with the currentconversation.

resumeTask(Long id) — associate the task with the given id with the currentconversation.

resumeProcess(Long id) — associate the process with the given id with the currentconversation.

transition(String transitionName) — trigger the transition.

org.jboss.seam.bpm.taskInstance

Manager component for the jBPM TaskInstance.

org.jboss.seam.bpm.processInstance

CHAPTER 28. BUILT-IN SEAM COMPONENTS

339

Page 345: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Manager component for the jBPM ProcessInstance.

org.jboss.seam.bpm.jbpmContext

Manager component for an event-scoped JbpmContext.

org.jboss.seam.bpm.taskInstanceList

Manager component for the jBPM task list.

org.jboss.seam.bpm.pooledTaskInstanceList

Manager component for the jBPM pooled task list.

org.jboss.seam.bpm.taskInstanceListForType

Manager component for the jBPM task lists.

org.jboss.seam.bpm.pooledTask

Action handler for pooled task assignment.

org.jboss.seam.bpm.processInstanceFinder

Manager for the process instance task list.

org.jboss.seam.bpm.processInstanceList

The process instance task list.

All of these components are installed whenever the component org.jboss.seam.bpm.jbpm isinstalled.

28.6. SECURITY-RELATED COMPONENTS

These components relate to web-tier security.

org.jboss.seam.web.userPrincipal

Manager component for the current user Principal.

org.jboss.seam.web.isUserInRole

Allows JSF pages to choose to render a control, depending upon the roles available to the currentprincipal. <h:commandButton value="edit" rendered="#{isUserInRole['admin']}"/>.

28.7. JMS-RELATED COMPONENTS

These components are for use with managed TopicPublishers and QueueSenders (see below).

org.jboss.seam.jms.queueSession

Manager component for a JMS QueueSession .

org.jboss.seam.jms.topicSession

Manager component for a JMS TopicSession .

Seam 2 Reference Guide

340

Page 346: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

28.8. MAIL-RELATED COMPONENTS

These components are for use with Seam's Email support

org.jboss.seam.mail.mailSession

Manager component for a JavaMail Session. The session can be either looked up in the JNDIcontext (by setting the sessionJndiName property) or it can created from the configurationoptions in which case the host is mandatory.

org.jboss.seam.mail.mailSession.host — the hostname of the SMTP server to use

org.jboss.seam.mail.mailSession.port — the port of the SMTP server to use

org.jboss.seam.mail.mailSession.username — the username to use to connect tothe SMTP server.

org.jboss.seam.mail.mailSession.password — the password to use to connect tothe SMTP server

org.jboss.seam.mail.mailSession.debug — enable JavaMail debugging (veryverbose)

org.jboss.seam.mail.mailSession.ssl — enable SSL connection to SMTP (willdefault to port 465)

org.jboss.seam.mail.mailSession.tls — by default true, enable TLS support in themail session

org.jboss.seam.mail.mailSession.sessionJndiName — name under which ajavax.mail.Session is bound to JNDI. If supplied, all other properties will be ignored.

28.9. INFRASTRUCTURAL COMPONENTS

These components provide critical platform infrastructure. You can install a component which isn'tinstalled by default by setting install="true" on the component in components.xml.

org.jboss.seam.core.init

Initialization settings for Seam. Always installed.

org.jboss.seam.core.init.jndiPattern — the JNDI pattern used for looking upsession beans

org.jboss.seam.core.init.debug — enable Seam debug mode. This should be set tofalse when in production. You may see errors if the system is placed under any load anddebug is enabled.

org.jboss.seam.core.init.userTransactionName — the JNDI name to use whenlooking up the JTA UserTransaction object.

org.jboss.seam.core.manager

Internal component for Seam page and conversation context management. Always installed.

CHAPTER 28. BUILT-IN SEAM COMPONENTS

341

Page 347: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

org.jboss.seam.core.manager.conversationTimeout — the conversation contexttimeout in milliseconds.

org.jboss.seam.core.manager.concurrentRequestTimeout — maximum wait timefor a thread attempting to gain a lock on the long-running conversation context.

org.jboss.seam.core.manager.conversationIdParameter — the requestparameter used to propagate the conversation id, default to conversationId.

org.jboss.seam.core.manager.conversationIsLongRunningParameter — therequest parameter used to propagate information about whether the conversation is long-running, default to conversationIsLongRunning.

org.jboss.seam.navigation.pages

Internal component for Seam workspace management. Always installed.

org.jboss.seam.navigation.pages.noConversationViewId — global setting forthe view id to redirect to when a conversation entry is not found on the server side.

org.jboss.seam.navigation.pages.loginViewId — global setting for the view id toredirect to when an unauthenticated user tries to access a protected view.

org.jboss.seam.navigation.pages.httpPort — global setting for the port to usewhen the http scheme is requested.

org.jboss.seam.navigation.pages.httpsPort — global setting for the port to usewhen the https scheme is requested.

org.jboss.seam.navigation.pages.resources — a list of resources to search for pages.xml style resources. Defaults to WEB-INF/pages.xml.

org.jboss.seam.bpm.jbpm

Bootstraps a JbpmConfiguration. Install as class org.jboss.seam.bpm.Jbpm.

org.jboss.seam.bpm.jbpm.processDefinitions — a list of resource names of jPDLfiles to be used for orchestration of business processes.

org.jboss.seam.bpm.jbpm.pageflowDefinitions — a list of resource names of jPDLfiles to be used for orchestration of conversation page flows.

org.jboss.seam.core.conversationEntries

Internal session-scoped component recording the active long-running conversations betweenrequests.

org.jboss.seam.faces.facesPage

Internal page-scoped component recording the conversation context associated with a page.

org.jboss.seam.persistence.persistenceContexts

Internal component recording the persistence contexts which were used in the currentconversation.

org.jboss.seam.jms.queueConnection

Seam 2 Reference Guide

342

Page 348: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Manages a JMS QueueConnection. Installed whenever managed managed QueueSender isinstalled.

org.jboss.seam.jms.queueConnection.queueConnectionFactoryJndiName —the JNDI name of a JMS QueueConnectionFactory. Default to UIL2ConnectionFactory

org.jboss.seam.jms.topicConnection

Manages a JMS TopicConnection. Installed whenever managed managed TopicPublisher isinstalled.

org.jboss.seam.jms.topicConnection.topicConnectionFactoryJndiName —the JNDI name of a JMS TopicConnectionFactory. Default to UIL2ConnectionFactory

org.jboss.seam.persistence.persistenceProvider

Abstraction layer for non-standardized features of JPA provider.

org.jboss.seam.core.validators

Caches instances of Hibernate Validator ClassValidator.

org.jboss.seam.faces.validation

Allows the application to determine whether validation failed or was successful.

org.jboss.seam.debug.introspector

Support for the Seam Debug Page.

org.jboss.seam.debug.contexts

Support for the Seam Debug Page.

org.jboss.seam.exception.exceptions

Internal component for exception handling.

org.jboss.seam.transaction.transaction

API for controlling transactions and abstracting the underlying transaction managementimplementation behind a JTA-compatible interface.

org.jboss.seam.faces.safeActions

Decides if an action expression in an incoming URL is safe. This is done by checking that the actionexpression exists in the view.

28.10. MISCELLANEOUS COMPONENTS

org.jboss.seam.async.dispatcher

Dispatcher stateless session bean for asynchronous methods.

org.jboss.seam.core.image

CHAPTER 28. BUILT-IN SEAM COMPONENTS

343

Page 349: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Image manipulation and interrogation.

org.jboss.seam.core.pojoCache

Manager component for a PojoCache instance.

org.jboss.seam.core.uiComponent

Manages a map of UIComponents keyed by component id.

28.11. SPECIAL COMPONENTS

Certain special Seam component classes are installable multiple times under names specified in theSeam configuration. For example, the following lines in components.xml install and configure twoSeam components:

The Seam component names are bookingDatabase and userDatabase.

<entityManager>, org.jboss.seam.persistence.ManagedPersistenceContext

Manager component for a conversation scoped managed EntityManager with an extendedpersistence context.

<entityManager>.entityManagerFactory — a value binding expression that evaluates to aninstance of EntityManagerFactory.

<entityManager>.persistenceUnitJndiName — the JNDI name of the entity manager factory,default to java:/<managedPersistenceContext>.

<entityManagerFactory>, org.jboss.seam.persistence.EntityManagerFactory

Manages a JPA EntityManagerFactory. This is most useful when using JPA outside of an EJB3.0 supporting environment.

entityManagerFactory.persistenceUnitName — the name of the persistence unit.

See the API JavaDoc for further configuration properties.

<session>, org.jboss.seam.persistence.ManagedSession

Manager component for a conversation scoped managed Hibernate Session.

<component name="bookingDatabase" class="org.jboss.seam.persistence.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/comp/emf/bookingPersistence</property></component>

<component name="userDatabase" class="org.jboss.seam.persistence.ManagedPersistenceContext"> <property name="persistenceUnitJndiName">java:/comp/emf/userPersistence</property></component>

Seam 2 Reference Guide

344

Page 350: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<session>.sessionFactory — a value binding expression that evaluates to an instance of SessionFactory.

<session>.sessionFactoryJndiName — the JNDI name of the session factory, default tojava:/<managedSession>.

<sessionFactory>, org.jboss.seam.persistence.HibernateSessionFactory

Manages a Hibernate SessionFactory.

<sessionFactory>.cfgResourceName — the path to the configuration file. Default to hibernate.cfg.xml.

See the API JavaDoc for further configuration properties.

<managedQueueSender>, org.jboss.seam.jms.ManagedQueueSender

Manager component for an event scoped managed JMS QueueSender.

<managedQueueSender>.queueJndiName — the JNDI name of the JMS queue.

<managedTopicPublisher>, org.jboss.seam.jms.ManagedTopicPublisher

Manager component for an event scoped managed JMS TopicPublisher.

<managedTopicPublisher>.topicJndiName — the JNDI name of the JMS topic.

<managedWorkingMemory>, org.jboss.seam.drools.ManagedWorkingMemory

Manager component for a conversation scoped managed Drools WorkingMemory.

<managedWorkingMemory>.ruleBase — a value expression that evaluates to an instance of RuleBase.

<ruleBase>, org.jboss.seam.drools.RuleBase

Manager component for an application scoped Drools RuleBase. Note that this is not really intendedfor production usage, since it does not support dynamic installation of new rules.

<ruleBase>.ruleFiles — a list of files containing Drools rules.

<ruleBase>.dslFile — a Drools DSL definition.

CHAPTER 28. BUILT-IN SEAM COMPONENTS

345

Page 351: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 29. SEAM JSF CONTROLSSeam includes a number of JSF controls that are useful for working with Seam. These are intended tocomplement the built-in JSF controls, and controls from other third-party libraries. We recommendJBoss RichFaces, and Apache MyFaces Trinidad tag libraries for use with Seam. We do not recommendthe use of the Tomahawk tag library.

29.1. TAGS

To use these tags, define the "s" namespace in your page as follows (facelets only):

The ui example demonstrates the use of a number of these tags.

29.1.1. Navigation Controls

29.1.1.1. <s:button>

Description

A button that supports invocation of an action with control over conversation propagation. Does notsubmit the form.

Attributes

value — the label.

action — a method binding that specified the action listener.

view — the JSF view id to link to.

fragment — the fragment identifier to link to.

disabled — is the link disabled?

propagation — determines the conversation propagation style: begin, join, nest, none or end.

pageflow — a pageflow definition to begin. (This is only useful when propagation="begin"or propagation="join" is used).

Usage

You can specify both view and action on <s:link />. In this case, the action will be called once theredirect to the specified view has occurred.

29.1.1.2. <s:conversationId>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:s="http://jboss.com/products/seam/taglib">

<s:button id="cancel" value="Cancel" action="#{hotelBooking.cancel}"/>

Seam 2 Reference Guide

346

Page 352: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Description

Add the conversation id to JSF link or button (e.g. <h:commandLink /> , <s:button />).

Attributes

None

29.1.1.3. <s:taskId>

Description

Add the task id to an output link (or similar JSF control), when the task is available via #{task}.

Attributes

None.

29.1.1.4. <s:link>

Description

A link that supports invocation of an action with control over conversation propagation. Does not submitthe form.

Attributes

value — the label.

action — a method binding that specified the action listener.

view — the JSF view id to link to.

fragment — the fragment identifier to link to.

disabled — is the link disabled?

propagation — determines the conversation propagation style: begin, join, nest, none or end.

pageflow — a pageflow definition to begin. (This is only useful when using propagation="begin" or propagation="join".)

Usage

You can specify both view and action on <s:link />. In this case, the action will be called once theredirect to the specified view has occurred.

29.1.1.5. <s:conversationPropagation>

Description

<s:link id="register" view="/register.xhtml" value="Register New User"/>

CHAPTER 29. SEAM JSF CONTROLS

347

Page 353: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Customize the conversation propagation for a command link or button (or similar JSF control). Faceletsonly.

Attributes

type — determines the conversation propagation style: begin, join, nest, none or end.

pageflow — a pageflow definition to begin. (This is only useful when using propagation="begin" or propagation="join".)

Usage

29.1.1.6. <s:defaultAction>

Description

Specify the default action to run when the form is submitted using the enter key.

Currently you can only nest it inside buttons (e.g. <h:commandButton />, <a:commandButton />or <tr:commandButton />).

You must specify an ID on the action source. You can only have one default action per form.

Attributes

None.

Usage

29.1.2. Converters and Validators

29.1.2.1. <s:convertDateTime>

Description

Perform date or time conversions in the Seam timezone.

Attributes

None.

Usage

<h:commandButton value="Apply" action="#{personHome.update}"> <s:conversationPropagation type="join" /></h:commandButton>

<h:commandButton id="foo" value="Foo" action="#{manager.foo}"> <s:defaultAction /></h:commandButton>

<h:outputText value="#{item.orderDate}"> <s:convertDateTime type="both" dateStyle="full"/></h:outputText>

Seam 2 Reference Guide

348

Page 354: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

29.1.2.2. <s:convertEntity>

Description

Assigns an entity converter to the current component. This is primarily useful for radio button anddropdown controls.

The converter works with any managed entity which has an @Id annotation - either simple orcomposite.

Attributes

None.

Configuration

You must use Seam managed transactions (see Section 10.2, “Seam managed transactions” ) with <s:convertEntity />.

If your Managed Persistence Context isn't called entityManager, then you need to set it incomponents.xml:

If you are using a Managed Hibernate Session then you need to set it in components.xml:

If you want to use more than one entity manager with the entity converter, you can create a copy ofthe entity converter for each entity manager in components.xml:

Usage

<component name="org.jboss.seam.ui.EntityConverter"> <property name="entityManager">#{em}</property></component>

<component name="org.jboss.seam.ui.EntityConverter"> <property name="session">#{hibernateSession}</property></component>

<component name="myEntityConverter" class="org.jboss.seam.ui.converter.EntityConverter"> <property name="entityManager">#{em}</property></component>

<h:selectOneMenu value="#{person.continent}"> <s:selectItems value="#{continents.resultList}" var="continent" label="#{continent.name}" /> <f:converter converterId="myEntityConverter" /></h:selectOneMenu>

<h:selectOneMenu value="#{person.continent}" required="true"> <s:selectItems value="#{continents.resultList}" var="continent" label="#{continent.name}" noSelectionLabel="Please Select..."/> <s:convertEntity /></h:selectOneMenu>

CHAPTER 29. SEAM JSF CONTROLS

349

Page 355: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

29.1.2.3. <s:convertEnum>

Description

Assigns an enum converter to the current component. This is primarily useful for radio button anddropdown controls.

Attributes

None.

Usage

29.1.2.4. <s:validate>

Description

A non-visual control, validates a JSF input field against the bound property using Hibernate Validator.

Attributes

None.

Usage

29.1.2.5. <s:validateAll>

Description

A non-visual control, validates all child JSF input fields against their bound properties using HibernateValidator.

Attributes

None.

Usage

<h:selectOneMenu value="#{person.honorific}"> <s:selectItems value="#{honorifics}" var="honorific" label="#{honorific.label}" noSelectionLabel="Please select" /> <s:convertEnum /></h:selectOneMenu>

<h:inputText id="userName" required="true" value="#{customer.userName}"> <s:validate /></h:inputText><h:message for="userName" styleClass="error" />

<s:validateAll> <div class="entry"> <h:outputLabel for="username">Username:</h:outputLabel> <h:inputText id="username" value="#{user.username}"

Seam 2 Reference Guide

350

Page 356: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

29.1.3. Formatting

29.1.3.1. <s:decorate>

Description

Decorate a JSF input field when validation fails or when required="true" is set.

Attributes

template — the facelets template to use to decorate the component

#{invalid} and #{required} are available inside s:decorate; #{required} evaluates to true ifyou have set the input component being decorated as required, and #{invalid} evaluates to true ifa validation error occurs.

Usage

required="true"/> <h:message for="username" styleClass="error" /> </div> <div class="entry"> <h:outputLabel for="password">Password:</h:outputLabel> <h:inputSecret id="password" value="#{user.password}" required="true"/> <h:message for="password" styleClass="error" /> </div> <div class="entry"> <h:outputLabel for="verify">Verify Password:</h:outputLabel> <h:inputSecret id="verify" value="#{register.verify}" required="true"/> <h:message for="verify" styleClass="error" /> </div></s:validateAll>

<s:decorate template="edit.xhtml"> <ui:define name="label">Country:</ui:define> <h:inputText value="#{location.country}" required="true"/> </s:decorate>

<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:s="http://jboss.com/products/seam/taglib"> <div> <s:label styleClass="#{invalid?'error':''}"> <ui:insert name="label"/> <s:span styleClass="required" rendered="#{required}">*</s:span> </s:label> <span class="#{invalid?'error':''}">

CHAPTER 29. SEAM JSF CONTROLS

351

Page 357: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

29.1.3.2. <s:div>

Description

Render a HTML <div>.

Attributes

None.

Usage

29.1.3.3. <s:span>

Description

Render a HTML <span>.

Attributes

None.

Usage

29.1.3.4. <s:fragment>

Description

A non-rendering component useful for enabling/disabling rendering of it's children.

Attributes

None.

Usage

<s:validateAll> <ui:insert/> </s:validateAll> </span> <s:message styleClass="error"/> </div> </ui:composition>

<s:div rendered="#{selectedMember == null}"> Sorry, but this member does not exist.</s:div>

<s:span styleClass="required" rendered="#{required}">*</s:span>

Seam 2 Reference Guide

352

Page 358: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

29.1.3.5. <s:label>

Description

Decorate a JSF input field with the label. The label is placed inside the HTML <label> tag, and isassociated with the nearest JSF input component. It is often used with <s:decorate>.

Attributes

style — The control's style

styleClass — The control's style class

Usage

29.1.3.6. <s:message>

Description

Decorate a JSF input field with the validation error message.

Attributes

None.

Usage

29.1.4. Seam Text

29.1.4.1. <s:validateFormattedText>

Description

Checks that the submitted value is valid Seam Text

Attributes

<s:fragment rendered="#{auction.highBidder ne null}"> Current bid:</s:fragment>

<s:label styleClass="label"> Country:</s:label><h:inputText value="#{location.country}" required="true"/>

<f:facet name="afterInvalidField"> <s:span> Error: <s:message/> </s:span></f:facet>

CHAPTER 29. SEAM JSF CONTROLS

353

Page 359: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

None.

29.1.4.2. <s:formattedText>

Description

Outputs Seam Text, a rich text markup useful for blogs, wikis and other applications that might use richtext. See the Seam Text chapter for full usage.

Attributes

value — an EL expression specifying the rich text markup to render.

Usage

Example

29.1.5. Dropdowns

29.1.5.1. <s:enumItem>

Description

Creates a SelectItem from an enum value.

Attributes

enumValue — the string representation of the enum value.

label — the label to be used when rendering the SelectItem.

<s:formattedText value="#{blog.text}"/>

Seam 2 Reference Guide

354

Page 360: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Usage

29.1.5.2. <s:selectItems>

Description

Creates a List<SelectItem> from a List, Set, DataModel or Array.

Attributes

value — an EL expression specifying the data that backs the List<SelectItem>

var— defines the name of the local variable that holds the current object during iteration

label — the label to be used when rendering the SelectItem. Can reference the varvariable.

itemValue — Value to return to the server if this option is selected. Optional, by default the var object is used. Can reference the var variable.

disabled — if true the SelectItem will be rendered disabled. Can reference the varvariable.

noSelectionLabel — specifies the (optional) label to place at the top of list (if required="true" is also specified then selecting this value will cause a validation error).

hideNoSelectionLabel — if true, the noSelectionLabel will be hidden when a value isselected

Usage

29.1.6. Other

29.1.6.1. <s:cache>

Description

Cache the rendered page fragment using JBoss Cache. Note that <s:cache> actually uses the

<h:selectOneRadio id="radioList" layout="lineDirection" value="#{newPayment.paymentFrequency}"> <s:convertEnum /> <s:enumItem enumValue="ONCE" label="Only Once" /> <s:enumItem enumValue="EVERY_MINUTE" label="Every Minute" /> <s:enumItem enumValue="HOURLY" label="Every Hour" /> <s:enumItem enumValue="DAILY" label="Every Day" /> <s:enumItem enumValue="WEEKLY" label="Every Week" /></h:selectOneRadio>

<h:selectOneMenu value="#{person.age}" converter="ageConverter"> <s:selectItems value="#{ages}" var="age" label="#{age}" /></h:selectOneMenu>

CHAPTER 29. SEAM JSF CONTROLS

355

Page 361: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

instance of JBoss Cache managed by the built-in pojoCache component.

Attributes

key — the key to cache rendered content, often a value expression. For example, if we werecaching a page fragment that displays a document, we might use key="Document-#{document.id}".

enabled — a value expression that determines if the cache should be used.

region — a JBoss Cache node to use (different nodes can have different expiry policies).

Usage

29.1.6.2. <s:fileUpload>

Description

Renders a file upload control. This control must be used within a form with an encoding type of multipart/form-data, for instance:

For multipart requests, the Seam Multipart servlet filter must also be configured in web.xml:

Configuration

<s:cache key="entry-#{blogEntry.id}" region="pageFragments"> <div class="blogEntry"> <h3>#{blogEntry.title}</h3> <div> <s:formattedText value="#{blogEntry.body}"/> </div> <p> [Posted on <h:outputText value="#{blogEntry.date}"> <f:convertDateTime timezone="#{blog.timeZone}" locale="#{blog.locale}" type="both"/> </h:outputText>] </p> </div></s:cache>

<h:form enctype="multipart/form-data">

<filter> <filter-name>Seam Filter</filter-name> <filter-class>org.jboss.seam.servlet.SeamFilter</filter-class></filter>

<filter-mapping> <filter-name>Seam Filter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

Seam 2 Reference Guide

356

Page 362: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

The following configuration options for multipart requests may be configured in components.xml:

createTempFiles — if this option is set to true, uploaded files are streamed to a temporaryfile instead of in memory.

maxRequestSize — the maximum size of a file upload request, in bytes.

Here's an example:

Attributes

data — this value binding receives the binary file data. The receiving field should be declared asa byte[] or InputStream (required).

contentType — this value binding receives the file's content type (optional).

fileName — this value binding receives the filename (optional).

fileSize — this value binding receives the file size (optional).

accept — a comma-separated list of content types to accept, may not be supported by thebrowser. E.g. "images/png,images/jpg", "images/*".

style — The control's style

styleClass — The control's style class

Usage

29.1.6.3. <s:graphicImage>

Description

An extended <h:graphicImage> that allows the image to be created in a Seam Component; furthertransforms can be applied to the image.

All attributes for <h:graphicImage> are supported, as well as:

Attributes

value — image to display. Can be a path String (loaded from the classpath), a byte[], a java.io.File, a java.io.InputStream or a java.net.URL. Currently supported imageformats are image/png, image/jpeg and image/gif.

fileName — if not specified the served image will have a generated file name. If you want toname your file, you should specify it here. This name should be unique

<component class="org.jboss.seam.web.MultipartFilter"> <property name="createTempFiles">true</property> <property name="maxRequestSize">1000000</property></component>

<s:fileUpload id="picture" data="#{register.picture}" accept="image/png" contentType="#{register.pictureContentType}" />

CHAPTER 29. SEAM JSF CONTROLS

357

Page 363: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Transformations

To apply a transform to the image, you would nest a tag specifying the transform to apply. Seamcurrently supports these transforms:

<s:transformImageSize>

width — new width of the image

height — new height of the image

maintainRatio — if true, and one of width/height are specified, the image will beresized with the dimension not specified being calculated to maintain the aspect ratio.

factor — scale the image by the given factor

<s:transformImageBlur>

radius — perform a convolution blur with the given radius

<s:transformImageType>

contentType — alter the type of the image to either image/jpeg or image/png

It is easy to create your own transform; create a UIComponent which implements org.jboss.seam.ui.graphicImage.ImageTransform. Inside the applyTransform()methoduse image.getBufferedImage() to get the original image and image.setBufferedImage() toset your transformed image. Transforms are applied in the order specified in the view.

Usage

29.1.6.4. <s:remote>

Description

Generates the Javascript stubs required to use Seam Remoting.

Attributes

include — a comma-separated list of the component names (or fully qualified class names)forwhich to generate Seam Remoting Javascript stubs. See Chapter 23, Remoting for moredetails.

Usage

29.2. ANNOTATIONS

<s:graphicImage rendered="#{auction.image ne null}" value="#{auction.image.data}"> <s:transformImageSize width="200" maintainRatio="true"/></s:graphicImage>

<s:remote include="customerAction,accountAction,com.acme.MyBean"/>

Seam 2 Reference Guide

358

Page 364: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Seam also provides annotations to allow you to use Seam components as JSF converters andvalidators:

@Converter

Registers the Seam component as a JSF converter. Shown here is a converter which is able toaccess the JPA EntityManager inside a JTA transaction, when converting the value back to it'sobject representation.

@Validator

Registers the Seam component as a JSF validator. Shown here is a validator which injects anotherSeam component; the injected component is used to validate the value.

@Name("itemConverter") @BypassInterceptors @Converter public class ItemConverter implements Converter { @Transactional public Object getAsObject(FacesContext context, UIComponent cmp, String value) { EntityManager entityManager = (EntityManager) Component.getInstance("entityManager"); entityManager.joinTransaction(); // Do the conversion } public String getAsString(FacesContext context, UIComponent cmp, Object value) { // Do the conversion } }

<h:inputText value="#{shop.item}" converter="itemConverter" />

@Name("itemValidator") @BypassInterceptors @Validator public class ItemValidator implements Validator { public void validate(FacesContext context, UIComponent cmp, Object value) throws ValidatorException { ItemController ItemController = (ItemController) Component.getInstance("itemController"); return itemController.validate(value); } }

<h:inputText value="#{shop.item}" validator="itemValidator" />

CHAPTER 29. SEAM JSF CONTROLS

359

Page 365: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 30. JBOSS EL

Seam uses JBoss EL which provides an extension to the standard Unified Expression Language (EL).JBoss EL provides a number of enhancements that increase the expressiveness and power of ELexpressions.

30.1. PARAMETRIZED EXPRESSIONS

Standard EL does not allow you to use a method with user defined parameters; JSF listener methods(for example, a valueChangeListener) take parameters provided by JSF.

JBoss EL removes this restriction. For example:

30.1.1. Usage

Just as in calls to method from Java, parameters are surrounded by parentheses, and separated bycommas:

The parameters hotel and user will be evaluated as value expressions and passed to the bookHotel() method of the component.

Any value expression may be used as a parameter:

It is important to fully understand how this extension to EL works. When the page is rendered, theparameter names are stored (for example, hotel.id and user.username), and evaluated (as valueexpressions) when the page is submitted. You cannot pass objects as parameters!

You must ensure that the parameters are available not only when the page is rendered, but also whenit is submitted. If the arguments can not be resolved when the page is submitted the action method willbe called with null arguments.

You can also pass literal strings using single quotes:

<h:commandButton action="#{hotelBooking.bookHotel(hotel)}" value="Book Hotel"/>

@Name("hotelBooking")public class HotelBooking { public String bookHotel(Hotel hotel) { // Book the hotel }}

<h:commandButton action="#{hotelBooking.bookHotel(hotel, user)}" value="Book Hotel"/>

<h:commandButton action="#{hotelBooking.bookHotel(hotel.id, user.username)}" value="Book Hotel"/>

<h:commandLink action="#{printer.println('Hello world!')}" value="Hello"/>

Seam 2 Reference Guide

360

Page 366: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Unified EL also supports value expressions, used to bind a field to a backing bean. Value expressionsuse JavaBean naming conventions and expect a getter/setter pair. Often JSF expects a valueexpression where only retrieval (get) is needed (for example, the rendered attribute). Many objects,however, don't have appropriately named property accessors or require parameters.

JBoss EL removes this restriction by allowing values to be retrieved using the method syntax. Forexample:

You can access the size of a collection in a similar manner:

In general any expression of the form #{obj.property} would be identical to the expression #{obj.getProperty()}.

Parameters are also allowed. The following example calls the productsByColorMethod with a literalstring argument:

30.1.2. Limitations and Hints

When using JBoss EL you should keep the following points in mind:

Incompatibility with JSP 2.1 — JBoss EL can't currently be used with JSP 2.1 as the compilerrejects expressions with parameters in. So, if you want to use this extension with JSF 1.2, youwill need to use Facelets. The extension works correctly with JSP 2.0.

Use inside iterative components — Components like <c:forEach /> and <ui:repeat />iterate over a List or array, exposing each item in the list to nested components. This worksgreat if you are selecting a row using a <h:commandButton /> or <h:commandLink />:

However if you want to use <s:link /> or <s:button /> you must expose the items as a DataModel, and use a <dataTable /> (or equivalent from a component set like <rich:dataTable /> ). Neither <s:link /> or <s:button /> submit the form (andtherefore produce a bookmarkable link) so another parameter is required to recreate the itemwhen the action method is called. This parameter can only be added when a data table backedby a DataModel is used.

<h:outputText value="#{person.name}" rendered="#{person.name.length() > 5}" />

#{searchResults.size()}

#{controller.productsByColor('blue')}

@Factory("items")public List<Item> getItems() { return entityManager.createQuery("select ...").getResultList();}

<h:dataTable value="#{items}" var="item"> <h:column> <h:commandLink value="Select #{item.name}" action="#{itemSelector.select(item})" /> </h:column></h:dataTable>

CHAPTER 30. JBOSS EL

361

Page 367: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Calling a MethodExpression from Java code — Normally, when a MethodExpression iscreated, the parameter types are passed in by JSF. In the case of a method binding, JSFassumes that there are no parameters to pass. With this extension, we cannot know theparameter types until after the expression has been evaluated. This has two minorconsequences:

When you invoke a MethodExpression in Java code, parameters you pass may beignored. Parameters defined in the expression will take precedence.

Ordinarily, it is safe to call methodExpression.getMethodInfo().getParamTypes()at any time. For an expression with parameters, you must first invoke the MethodExpression before calling getParamTypes().

Both of these cases are exceedingly rare and only apply when you want to invoke the MethodExpression by hand in Java code.

30.2. PROJECTION

JBoss EL supports a limited projection syntax. A projection expression maps a sub-expression across amulti-valued (list, set, etc...) expression. For instance, the expression:

might return a list of departments. If you only need a list of department names, your only option is toiterate over the list to retrieve the values. JBoss EL allows this with a projection expression:

The subexpression is enclosed in braces. In this example, the expression d.name is evaluated for eachdepartment, using d as an alias to the department object. The result of this expression will be a list ofString values.

Any valid expression can be used in an expression, so it would be perfectly valid to write the following,assuming you had a use for the lengths of all the department names in a company:

Projections can be nested. The following expression returns the last names of every employee in everydepartment:

Nested projections can be slightly tricky, however. The following expression looks like it returns a listof all the employees in all the departments:

However, it actually returns a list containing a list of the employees for each individual department. Tocombine the values, it is necessary to use a slightly longer expression:

#{company.departments}

#{company.departments.{d|d.name}}

#{company.departments.{d|d.size()}}

#{company.departments.{d|d.employees.{emp|emp.lastName}}}

#{company.departments.{d|d.employees}}

#{company.departments.{d|d.employees.{e|e}}}

Seam 2 Reference Guide

362

Page 368: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

It is important to note that this syntax cannot be parsed by Facelets or JSP and thus cannot be used inxhtml or JSP files. We anticipate that the projection syntax will change in future versions of JBoss EL.

CHAPTER 30. JBOSS EL

363

Page 369: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 31. TESTING SEAM APPLICATIONS

Most Seam applications will need at least two kinds of automated tests: unit tests, which test aparticular Seam component in isolation, and scripted integration tests which exercise all Java layers ofthe application (that is, everything except the view pages).

Both kinds of tests are very easy to write.

31.1. UNIT TESTING SEAM COMPONENTS

All Seam components are POJOs. This is a great place to start if you want easy unit testing. And sinceSeam emphasizes the use of bijection for inter-component interactions and access to contextualobjects, it is very easy to test a Seam component outside of its normal runtime environment.

Consider the following Seam Component which creates a statement of account for a customer:

We could write a unit test for the calculateTotal method (which tests the business logic of thecomponent) as follows:

@Stateless@Scope(EVENT)@Name("statementOfAccount")public class StatementOfAccount { @In(create=true) EntityManager entityManager private double statementTotal; @In private Customer customer; @Create public void create() { List<Invoice> invoices = entityManager .createQuery("select invoice from Invoice invoice where invoice.customer = :customer") .setParameter("customer", customer) .getResultList(); statementTotal = calculateTotal(invoices); } public double calculateTotal(List<Invoice> invoices) { double total = 0.0; for (Invoice invoice: invoices) { double += invoice.getTotal(); } return total; } // getter and setter for statementTotal }

public class StatementOfAccountTest {

Seam 2 Reference Guide

364

Page 370: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

You will notice we are not testing the retrieving of data from or persisting of data to the database; norare we testing any functionality provided by Seam. We are just testing the logic of our POJOs. Seamcomponents don't usually depend directly upon container infrastructure, so most unit testing as aseasy as that.

However, if you want to test the entire application, read on.

31.2. INTEGRATION TESTING SEAM COMPONENTS

Integration testing is slightly more difficult. In this case, we cannot eliminate the containerinfrastructure; indeed, that is part of what is being tested. At the same time, we do not want to beforced to deploy our application to an application server to run the automated tests. We need to be ableto reproduce just enough of the container infrastructure inside our testing environment to be able toexercise the whole application, without hurting performance too much.

The approach taken by Seam is to let you write tests that exercise your components while runninginside a pruned down container environment (Seam, together with the JBoss Embedded container; n.b.JBoss Embedded requires JDK 1.5 and does not work with JDK 1.6).

@Test public testCalculateTotal { List<Invoice> invoices = generateTestInvoices(); // A test data generator double statementTotal = new StatementOfAccount().calculateTotal(invoices); assert statementTotal = 123.45; } }

public class RegisterTest extends SeamTest{ @Test public void testRegisterComponent() throws Exception { new ComponentTest() {

protected void testComponents() throws Exception { setValue("#{user.username}", "1ovthafew"); setValue("#{user.name}", "Gavin King"); setValue("#{user.password}", "secret"); assert invokeMethod("#{register.register}").equals("success"); assert getValue("#{user.username}").equals("1ovthafew"); assert getValue("#{user.name}").equals("Gavin King"); assert getValue("#{user.password}").equals("secret"); } }.run(); }

...

CHAPTER 31. TESTING SEAM APPLICATIONS

365

Page 371: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

31.2.1. Using mocks in integration tests

Occasionally, we need to be able to replace the implementation of some Seam component thatdepends upon resources which are not available in the integration test environment. For example,suppose we have some Seam component which is a facade to some payment processing system:

For integration tests, we can mock out this component as follows:

Since the MOCK precedence is higher than the default precedence of application components, Seam willinstall the mock implementation whenever it is in the classpath. When deployed into production, themock implementation is absent, so the real component will be installed.

31.3. INTEGRATION TESTING SEAM APPLICATION USERINTERACTIONS

An even harder problem is emulating user interactions. A third problem is where to put our assertions.Some test frameworks let us test the whole application by reproducing user interactions with the webbrowser. These frameworks have their place, but they are not appropriate for use at development time.

SeamTest lets you write scripted tests, in a simulated JSF environment. The role of a scripted test is toreproduce the interaction between the view and the Seam components. In other words, you get topretend you are the JSF implementation!

This approach tests everything except the view.

Let us consider a JSP view for the component we unit tested above:

}

@Name("paymentProcessor")public class PaymentProcessor { public boolean processPayment(Payment payment) { .... }}

@Name("paymentProcessor")@Install(precedence=MOCK)public class MockPaymentProcessor extends PaymentProcessor { public boolean processPayment(Payment payment) { return true; }}

<html> <head> <title>Register New User</title> </head> <body> <f:view> <h:form> <table border="0"> <tr> <td>Username</td> <td><h:inputText value="#{user.username}"/></td> </tr>

Seam 2 Reference Guide

366

Page 372: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

We want to test the registration functionality of our application (the stuff that happens when the userclicks the Register button). We will reproduce the JSF request lifecycle in an automated TestNG test:

<tr> <td>Real Name</td> <td><h:inputText value="#{user.name}"/></td> </tr> <tr> <td>Password</td> <td><h:inputSecret value="#{user.password}"/></td> </tr> </table> <h:messages/> <h:commandButton type="submit" value="Register" action="#{register.register}"/> </h:form> </f:view> </body></html>

public class RegisterTest extends SeamTest{ @Test public void testRegister() throws Exception { new FacesRequest() {

@Override protected void processValidations() throws Exception { validateValue("#{user.username}", "1ovthafew"); validateValue("#{user.name}", "Gavin King"); validateValue("#{user.password}", "secret"); assert !isValidationFailure(); } @Override protected void updateModelValues() throws Exception { setValue("#{user.username}", "1ovthafew"); setValue("#{user.name}", "Gavin King"); setValue("#{user.password}", "secret"); }

@Override protected void invokeApplication() { assert invokeMethod("#{register.register}").equals("success"); }

@Override protected void renderResponse() { assert getValue("#{user.username}").equals("1ovthafew");

CHAPTER 31. TESTING SEAM APPLICATIONS

367

Page 373: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Notice that we have extended SeamTest, which provides a Seam environment for our components, andwritten our test script as an anonymous class that extends SeamTest.FacesRequest, which providesan emulated JSF request lifecycle. (There is also a SeamTest.NonFacesRequest for testing GETrequests.) We have written our code in methods which are named for the various JSF phases, toemulate the calls that JSF would make to our components; then we have thrown in various assertions.

You will find plenty of integration tests for the Seam example applications which demonstrate morecomplex cases. There are instructions for running these tests using Ant, or using the TestNG plugin foreclipse:

assert getValue("#{user.name}").equals("Gavin King"); assert getValue("#{user.password}").equals("secret"); } }.run(); }

... }

Seam 2 Reference Guide

368

Page 374: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

31.3.1. Configuration

If you used seam-gen to create your project you are ready to start writing tests. Otherwise you willneed to setup the testing environment in your favorite build tool (for example, ant, maven, eclipse).

First, lets look at the dependencies you need at a minimum:

CHAPTER 31. TESTING SEAM APPLICATIONS

369

Page 375: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Table 31.1.

Group Id Artifact Id Location in Seam

org.jboss.seam.embedded hibernate-all lib/test/hibernate-all.jar

org.jboss.seam.embedded jboss-embedded-all lib/test/jboss-embedded-all.jar

org.jboss.seam.embedded thirdparty-all lib/test/thirdparty-all.jar

org.jboss.seam.embedded jboss-embedded-api lib/jboss-embedded-api.jar

org.jboss.seam jboss-seam lib/jboss-seam.jar

org.jboss.el jboss-el lib/jboss-el.jar

javax.faces jsf-api lib/jsf-api.jar

javax.activation javax.activation lib/activation.jar

It is very important that you do not put the compile time JBoss AS dependencies from lib/ (forexample, jboss-system.jar) on the classpath, these will cause Embedded JBoss to not boot. So,just add the dependencies (for example, Drools, jBPM) you need as you go.

You also need to include the bootstrap/ directory on the classpath; bootstrap/ contains theconfiguration for Embedded JBoss.

And, of course you need to put your built project and tests onto the classpath. Do not forget to put allthe correct configuration files for JPA and Seam onto the classpath as well.Seam asks EmbeddedJBoss to deploy any resource (jar or directory) which has seam.properties in it's root. Therefore, ifyou don't assemble a directory structure that resembles a deployable archive containing your builtproject, you must put a seam.properties in each resource.

By default, a generated project will use the java:/DefaultDS (a built in HSQL datasource inEmbedded JBoss) for testing. If you want to use another datasource place the foo-ds.xml into bootstrap/deploy directory.

31.3.2. Using SeamTest with another test framework

Seam provides TestNG support out of the box, but you can also use another test framework, such asJUnit, if you want.

You will need to provide an implementation of AbstractSeamTest which does the following:

Calls super.begin() before every test method.

Calls super.end() after every test method.

Seam 2 Reference Guide

370

Page 376: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Calls super.setupClass() to setup integration test environment. This should be calledbefore any test methods are called.

Calls super.cleanupClass() to clean up the integration test environment.

Calls super.startSeam() to start Seam at the start of integration testing.

Calls super.stopSeam() to cleanly shut down Seam at the end of integration testing.

31.3.3. Integration Testing with Mock Data

If you need to insert or clean data in your database before each test you can use Seam's integrationwith DBUnit. To do this, extend DBUnitSeamTest rather than SeamTest.

You need to provide a dataset for DBUnit. IMPORTANT NOTE: DBUnit supports two formats for datasetfiles, flat and XML. Seam's DBUnitSeamTest assumes the flat format is used, so please ensure thatyour dataset is in this format also.

and tell Seam about it by overriding prepareDBUnitOperations():

DataSetOperation defaults to DatabaseOperation.CLEAN_INSERT if no other operation isspecified as a constructor argument. The above example cleans all tables defined BaseData.xml,then inserts all rows declared in BaseData.xml before each @Test method is invoked.

If you require extra cleanup after a test method executes, add operations to afterTestOperationslist.

You need to tell DBUnit about the datasource you are using by setting a TestNG test parameter named datasourceJndiName:

<dataset> <ARTIST id="1" dtype="Band" name="Pink Floyd" /> <DISC id="1" name="Dark Side of the Moon" artist_id="1" /> </dataset>

protected void prepareDBUnitOperations() { beforeTestOperations.add( new DataSetOperation("my/datasets/BaseData.xml") ); }

<parameter name="datasourceJndiName" value="java:/seamdiscsDatasource"/>

CHAPTER 31. TESTING SEAM APPLICATIONS

371

Page 377: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

DBUnitSeamTest only works out of the box with HSQL as a datasource. If you want to use anotherdatabase, then you'll need to implement some extra methods. Read the javadoc on DBUnitSeamTestfor more.

31.3.4. Integration Testing Seam Mail

WARNING

This feature is still under development.

It is very easy to integration test your Seam Mail:

We create a new FacesRequest as normal. Inside the invokeApplication hook we render the messageusing getRenderedMailMessage(viewId);, passing the viewId of the message to render. Themethod returns the rendered message on which you can do your tests. You can of course also use anyof the standard JSF lifecycle methods.

There is no support for rendering standard JSF components so you cannot test the content body of themail message easily.

public class MailTest extends SeamTest { @Test public void testSimpleMessage() throws Exception { new FacesRequest() {

@Override protected void updateModelValues() throws Exception { setValue("#{person.firstname}", "Pete"); setValue("#{person.lastname}", "Muir"); setValue("#{person.address}", "[email protected]"); } @Override protected void invokeApplication() throws Exception { MimeMessage renderedMessage = getRenderedMailMessage("/simple.xhtml"); assert renderedMessage.getAllRecipients().length == 1; InternetAddress to = (InternetAddress) renderedMessage.getAllRecipients()[0]; assert to.getAddress().equals("[email protected]"); } }.run(); }}

Seam 2 Reference Guide

372

Page 378: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 32. SEAM TOOLS

32.1. JBPM DESIGNER AND VIEWER

The jBPM designer and viewer will let you design and view in a nice way your business processes andyour pageflows. This convenient tool is part of JBoss Eclipse IDE and more details can be found in thejBPM's documentation (http://docs.jboss.com/jbpm/v3/gpd/)

32.1.1. Business process designer

This tool lets you design your own business process in a graphical way.

Figure 32.1. Business process designer

32.1.2. Pageflow viewer

This tool let you design to some extend your pageflows and let you build graphical views of them soyou can easily share and compare ideas on how it should be designed.

CHAPTER 32. SEAM TOOLS

373

Page 379: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Figure 32.2. Business process designer

Seam 2 Reference Guide

374

Page 380: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

CHAPTER 33. DEPENDENCIES

33.1. JDK DEPENDENCIES

Seam does not work with JDK 1.4 and requires JDK 5 or above as it uses annotations and other JDK5.0 features.. Seam has been thoroughly tested using Sun's JDKs. However there are no known issuesspecific to Seam with other JDK's.

33.1.1. Sun's JDK 6 Considerations

Earlier versions of Sun's JDK 6 contained an incompatible version of JAXB and required overriding itusing the endorsed directory. Sun's JDK6 Update 4 release upgraded to JAXB 2.1 and removed thisrequirement. When building, testing, or executing be sure to use this version or higher.

Seam used JBoss Embedded in its unit and integration testing. This has an additional requirementwhen using JDK 6. In order to run JBoss Embedded with JDK 6 you need to set the following JVMargument:

Seam's internal build system is setting this by default when it executes Seam's test suite. However ifyou are also using JBoss Embedded for your testing you will need to set this value.

33.2. PROJECT DEPENDENCIES

This section both lists the compile-time and runtime dependencies for Seam. Where the type is listedas ear, the library should be included in the /lib directory of your application's ear file. Where the typeis listed as war, the library should be placed in the /WEB-INF/lib directory of your application's warfile. The scope of the dependency is either all, runtime or provided (by JBoss EAP 4.3).

Up to date version information and complete dependency information is not included in the docs, but isprovided in the /dependency-report.txt which is generated from the Maven POMs stored in /build. You can generate this file by running ant dependencyReport.

33.2.1. Core

Table 33.1.

Name Scope Type Notes

jboss-seam.jar all ear The core Seam library,always required.

jboss-seam-debug.jar

runtime war Include duringdevelopment whenenabling Seam's debugfeature

jboss-seam-ioc.jar

runtime war Required when usingSeam with Spring

-Dsun.lang.ClassLoader.allowArraySyntax=true

CHAPTER 33. DEPENDENCIES

375

Page 381: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

jboss-seam-pdf.jar

runtime war Required when usingSeam's PDF features

jboss-seam-remoting.jar

runtime war Required when usingSeam Remoting

jboss-seam-ui.jar

runtime war Required to use theSeam JSF controls

jsf-api.jar provided JSF API

jsf-impl.jar provided JSF ReferenceImplementation

jsf-facelets.jar runtime war Facelets

urlrewrite.jar runtime war URL Rewrite library

quartz.jar runtime ear Required when you wishto use Quartz withSeam's asynchronousfeatures

Name Scope Type Notes

33.2.2. RichFaces

Table 33.2. RichFaces dependencies

Name Scope Type Notes

richfaces-api.jar

all ear Required to useRichFaces. Provides APIclasses that you maywish to use from yourapplication e.g. tocreate a tree

richfaces-impl.jar

runtime war Required to useRichFaces.

richfaces-ui.jar runtime war Required to useRichFaces. Provides allthe UI components.

33.2.3. Seam Mail

Table 33.3. Seam Mail Dependencies

Seam 2 Reference Guide

376

Page 382: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Name Scope Type Notes

activation.jar runtime ear Required forattachment support

mail.jar runtime ear Required for outgoingmail support

mail-ra.jar compile only Required for incomingmail support

mail-ra.rar should bedeployed to theapplication server atruntime

jboss-seam-mail.jar

runtime war Seam Mail

33.2.4. Seam PDF

Table 33.4. Seam PDF Dependencies

Name Type Scope Notes

itext.jar runtime war PDF Library

jfreechart.jar runtime war Charting library

jcommon.jar runtime war Required by JFreeChart

jboss-seam-pdf.jar

runtime war Seam PDF core library

33.2.5. JBoss Rules

The JBoss Rules libraries can be found in the drools/lib directory in Seam.

Table 33.5. JBoss Rules Dependencies

Name Scope Type Notes

antlr-runtime.jar

runtime ear ANTLR Runtime Library

core.jar runtime ear Eclipse JDT

drools-compiler.jar

runtime ear

CHAPTER 33. DEPENDENCIES

377

Page 383: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

drools-core.jar runtime ear

janino.jar runtime ear

mvel.jar runtime ear

Name Scope Type Notes

33.2.6. JBPM

Table 33.6. JBPM dependencies

Name Scope Type Notes

jbpm-jpdl.jar runtime ear

33.2.7. GWT

These libraries are required if you with to use the Google Web Toolkit (GWT) with your Seamapplication.

NOTE

GWT in Seam is marked as technology preview, so standard support is not guaranteed.

Table 33.7. GWT dependencies

Name Scope Type Notes

gwt-servlet.jar runtime war The GWT Servlet libs

33.2.8. Spring

These libraries are required if you with to use the Spring Framework with your Seam application.

NOTE

Spring integration in Seam is marked as technology preview, so standard support is notguaranteed.

Table 33.8. Spring Framework dependencies

Seam 2 Reference Guide

378

Page 384: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

Name Scope Type Notes

spring.jar runtime ear The Spring Frameworklibrary

33.2.9. Groovy

These libraries are required if you with to use Groovy with your Seam application.

NOTE

Groovy integration in Seam is marked as technology preview, so standard support is notguaranteed.

Table 33.9. Groovy dependencies

Name Scope Type Notes

groovy-all.jar runtime ear The Groovy libs

33.3. DEPENDENCY MANAGEMENT USING MAVEN

Maven offers support for transitive dependency management and can be used to manage thedependencies of your Seam project. You can use Maven Ant Tasks to integrate Maven into your Antbuild, or can use Maven to build and deploy your project.

We are not actually going to discuss how to use Maven here, but just run over some basic POMs youcould use.

Released versions of Seam are available in http://repository.jboss.org/maven2 and nightly snapshotsare available in http://snapshots.jboss.org/maven2.

All the Seam artifacts are available in Maven:

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam</artifactId></dependency>

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam-ui</artifactId></dependency>

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam-pdf</artifactId></dependency>

CHAPTER 33. DEPENDENCIES

379

Page 385: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

This sample POM will give you Seam, JPA (provided by Hibernate) and Hibernate Validator:

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam-remoting</artifactId></dependency>

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam-ioc</artifactId></dependency>

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam-ioc</artifactId></dependency>

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.jboss.seam.example/groupId> <artifactId>my-project</artifactId> <version>1.0</version> <name>My Seam Project</name> <packaging>jar</packaging> <repositories> <repository> <id>repository.jboss.org</id> <name>JBoss Repository</name> <url>http://repository.jboss.org/maven2</url> </repository> </repositories>

<dependencies>

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>3.0.0.GA</version> </dependency>

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.3.0.ga</version> </dependency>

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId>

Seam 2 Reference Guide

380

Page 386: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

<version>3.3.1.ga</version> </dependency>

<dependency> <groupId>org.jboss.seam</groupId> <artifactId>jboss-seam</artifactId> <version>2.0.0.GA</version> </dependency> </dependencies>

</project>

CHAPTER 33. DEPENDENCIES

381

Page 387: JBoss Enterprise Application Platform 4.3 Seam 2 · PDF fileThe JSF configuration: ... 1.6.5. The Seam Debug Page 1.7. ... JBoss Enterprise Application Platform 4.3 Seam 2 Reference

APPENDIX A. REVISION HISTORY

Revision 4.3.10-100.33.400 2013-10-31 Rüdiger LandmannRebuild with publican 4.0.0

Revision 4.3.10-100.33 July 24 2012 Ruediger LandmannRebuild for Publican 3.0

Revision 4.3.10-100 Mon Aug 29 2011 Jared MorganIncorporated changes for the Enterprise Application Platform 4.3.0CP10 release. For more information, refer to theDocumentation Resolved Issues in the Release Notes CP10.

Revision 4.3.9-100 Tue Nov 30 2010 Jared MorganIncorporated changes for the Enterprise Application Platform 4.3.0CP09 release. For more information, refer to theDocumentation Resolved Issues in the Release Notes CP09.

Seam 2 Reference Guide

382