Seam - Контекстуальные Компоненты SeamFramework.orgCommunity Документация. Seam - Контекстуальные Компоненты. A Framework for Enterprise Java by Gavin King, Pete Muir, Norman Richards, Shane Bryzak, Michael Yuan, Mike Youngstrom, Christian Bauer, Jay Balunas, Dan Allen, Max Rydahl Andersen, Emmanuel Bernard, Nicklas Karlsson, Daniel Roth, Matt Drees, Jacob Orshalick, и Marek Novotny отредактировано Samson Kittoli: и спасибо James Cobb (Графический дизайн), Cheyenne Weaver (Графический дизайн), Mark Newton, Steve Ebersole, и Michael Courcy (Французский переаод) 2.1.1.CR2 Введение в JBoss Seam 1. Сотрудничество с Seam 1. Seam. Знакомство. 1.1 Использование примеров Seam 1.1.1 Запуск примеров на JBoss AS 1.1.2 Запуск примеров на Tomcat 1.1.3 Запуск тестовых примеров 1.2 Ваше первое Seam приложение: регистрационный пример. 1.2.1 Объяснение кода 1.2.2 Как это работает 1.3. Список в Seam: пример сообщений 1.3.1 Объяснение кода 1.3.2 Как это работает 1.4. Seam и jBPM: пример список задач. 1.4.1 Объяснение кода 1.4.2 Как это работает 1.5. Seam страничный поток: пример "угадай числа" 1.5.1 Объяснение кода 1.5.2 Как это работает 1.6 Законченное Seam приложение: пример "Книга отеля" 1.6.1 Введение 1.6.2 Обзор примеров 1.6.3 1.6.4 Seam. Страница отладки 1.7. Nested conversations: extending the Hotel Booking example 1.7.1. Introduction 1.7.2. Understanding Nested Conversations 1.8. A complete application featuring Seam and jBPM: the DVD Store example 1.9. Bookmarkable URLs with the Blog example 1.9.1. Using "pull"-style MVC 1.9.2. Bookmarkable search results page 1.9.3. Using "push"-style MVC in a RESTful application 2. Getting started with Seam, using seam-gen 2.1. Before you start 2.2. Setting up a new Eclipse project 2.3. Creating a new action 2.4. Creating a form with an action 2.5. Generating an application from an existing database 2.6. Generating an application from existing JPA/EJB3 entities 2.7. Deploying the application as an EAR 2.8. Seam and incremental hot deployment 2.9. Using Seam with JBoss 4.0 2.9.1 Установка JBoss 4.0 2.9.2 Установка JSF 1.2 RI 3. Начало работы с Seam, использование инструментов JBoss 3.1 Перед тем, как начать 3.2 Создание нового Seam-проекта 3.3 Создание нового действия 3.4 Создание формы с действием 3.5 Создание приложения из существующей базы данных 3.6 Seam и пошаговое исполнение инструментами JBoss Контекстно-компонентная модель 4.1. Среда исполнения Seam 4.1.1 4.1.2 Среда событий 4.1.3 Среда страницы 4.1.4 Среда диалога 4.1.5 Среда сессии 4.1.6 Среда бизнес-процесса 4.1.7 Среда приложения 4.1.8 Среда переменных 4.1.9 Среда приоритета поиска 4.1.10 Совмещенная модель 4.2 Компоненты Seam 4.2.1. Stateless session beans 4.2.2. Stateful session beans 4.2.3. Entity beans 4.2.4. JavaBeans 4.2.5. Message-driven beans 4.2.6. Interception 4.2.7. Component names 4.2.8. Defining the component scope 4.2.9. Components with multiple roles 4.2.10. Built-in components 4.3. Bijection 4.4. Lifecycle methods 4.5. Conditional installation 4.6. Logging 4.7. The Mutable interface and @ReadOnly 4.8. Factory and manager components 5. Конфигурирование компонентов Seam 5.1. Configuring components via property settings 5.2. Configuring components via components.xml 5.3. Fine-grained configuration files 5.4. Configurable property types 5.5. Using XML Namespaces 6. События, перехватчики и обработчики исключений 6.1 Seam события 6.2 Действия страницы 6.3 Параметры страницы 6.3.1 Сопоставление параметров запроса в модели 6.4. Propagating request parameters 6.5. URL rewriting with page parameters 6.6. Conversion and Validation 6.7. Navigation 6.8. Fine-grained files for definition of navigation, page actions and parameters 6.9. Component-driven events 6.10. Contextual events 6.11. Seam interceptors 6.12. Managing exceptions 6.12.1 Исключения и транзакции 6.12.2 Доступные обработчики исключений Seam 6.12.3 Использование описаний в обработчике исключений 6.12.4 Использование XML в обработчике исключений 6.12.5 Некоторые стандартные исключения 6.13. conversation-required 7. Conversations and workspace management 7.1. Seam's conversation model 7.2. Nested conversations 7.3. Starting conversations with GET requests 7.4. Using and 7.5. Success messages 7.6. Natural conversation ids 7.7. Creating a natural conversation 7.8. Redirecting to a natural conversation 7.9. Workspace management 7.9.1. Workspace management and JSF navigation 7.9.2. Workspace management and jPDL pageflow 7.9.3. The conversation switcher 7.9.4. The conversation list 7.9.5. Breadcrumbs 7.10. Conversational components and JSF component bindings 7.11. Concurrent calls to conversational components 7.11.1 Как мы должны разрабатывать диалоговые AJAX-приложения? 7.11.2 Работа с ошибками 7.11.3 Многоликий AJAX 8. Страничные потоки и бизнес-процессы 8.1. Страничные потоки в Seam 8.1.1 Двунаправленная модель 8.1.2 Seam и кнопка возврата 8.2. Использование jPDL страничных потоков 8.2.1 Установка страничных потоков 8.2.2 Начало страничных потоков 8.2.3 Узлы страницы и переходы 8.2.4 Управление потоком 8.2.5 Завершение потока 8.2.6 Структура страничных потоков 8.3. Управление бизнес-процессами в Seam 8.4 Использование jPDL-объявления бизнес-процессов 8.4.1. Installing process definitions 8.4.2. Initializing actor ids 8.4.3. Initiating a business process 8.4.4. Task assignment 8.4.5. Task lists 8.4.6. Performing a task 9. Seam and Object/Relational Mapping 9.1. Introduction 9.2. Seam managed transactions 9.2.1. Disabling Seam-managed transactions 9.2.2. Configuring a Seam transaction manager 9.2.3. Transaction synchronization 9.3. Seam-managed persistence contexts 9.3.1. Using a Seam-managed persistence context with JPA 9.3.2. Using a Seam-managed Hibernate session 9.3.3. Seam-managed persistence contexts and atomic conversations 9.4. Using the JPA "delegate" 9.5. Using EL in EJB-QL/HQL 9.6. Using Hibernate filters 10. JSF form validation in Seam 11. Groovy integration 11.1. Groovy introduction 11.2. Writing Seam applications in Groovy 11.2.1. Writing Groovy components 11.2.2. seam-gen 11.3. Deployment 11.3.1. Deploying Groovy code 11.3.2. Native .groovy file deployment at development time 11.3.3. seam-gen 12. Writing your presentation layer using Apache Wicket 12.1. Adding Seam to your wicket application 12.1.1. Bijection 12.1.2. Orchestration 12.2. Setting up your project 12.2.1. Defining the Application 13. The Seam Application Framework 13.1. Introduction 13.2. Home objects 13.3. Query objects 13.4. Controller objects 14. Seam and JBoss Rules 14.1. Installing rules 14.2. Using rules from a Seam component 14.3. Using rules from a jBPM process definition 15. Security 15.1. Overview 15.2. Disabling Security 15.3. Authentication 15.3.1. Configuring an Authenticator component 15.3.2. Writing an authentication method 15.3.3. Writing a login form 15.3.4. Configuration Summary 15.3.5. Remember Me 15.3.6. Handling Security Exceptions 15.3.7. Login Redirection 15.3.8. HTTP Authentication 15.3.9. Advanced Authentication Features 15.4. Identity Management 15.4.1. Configuring IdentityManager 15.4.2. JpaIdentityStore 15.4.3. LdapIdentityStore 15.4.4. Writing your own IdentityStore 15.4.5. Authentication with Identity Management 15.4.6. Using IdentityManager 15.5. Error Messages 15.6. Authorization 15.6.1. Core concepts 15.6.2. Securing components 15.6.3. Security in the user interface 15.6.4. Securing pages 15.6.5. Securing Entities 15.6.6. Typesafe Permission Annotations 15.6.7. Typesafe Role Annotations 15.6.8. The Permission Authorization Model 15.6.9. RuleBasedPermissionResolver 15.6.10. PersistentPermissionResolver 15.7. Permission Management 15.7.1. PermissionManager 15.7.2. Permission checks for PermissionManager operations 15.8. SSL Security 15.8.1. Overriding the default ports 15.9. CAPTCHA 15.9.1. Configuring the CAPTCHA Servlet 15.9.2. Adding a CAPTCHA to a form 15.9.3. Customising the CAPTCHA algorithm 15.10. Security Events 15.11. Run As 15.12. Extending the Identity component 15.13. OpenID 15.13.1. Configuring OpenID 15.13.2. Presenting an OpenIdDLogin form 15.13.3. Logging in immediately 15.13.4. Deferring login 15.13.5. Logging out 16. Internationalization, localization and themes 16.1. Internationalizing your app 16.1.1. Application server configuration 16.1.2. Translated application strings 16.1.3. Other encoding settings 16.2. Locales 16.3. Labels 16.3.1. Defining labels 16.3.2. Displaying labels 16.3.3. Faces messages 16.4. Timezones 16.5. Themes 16.6. Persisting locale and theme preferences via cookies 17. Seam Text 17.1. Basic fomatting 17.2. Entering code and text with special characters 17.3. Links 17.4. Entering HTML 18. iText PDF generation 18.1. Using PDF Support 18.1.1. Creating a document 18.1.2. Basic Text Elements 18.1.3. Headers and Footers 18.1.4. Chapters and Sections 18.1.5. Lists 18.1.6. Tables 18.1.7. Document Constants 18.2. Charting 18.3. Bar codes 18.4. Fill-in-forms 18.5. Rendering Swing/AWT components 18.6. Configuring iText 18.7. Further documentation 19. The Microsoft® Excel® spreadsheet application 19.1. The Microsoft® Excel® spreadsheet application support 19.2. Creating a simple workbook 19.3. Workbooks 19.4. Worksheets 19.5. Columns 19.6. Cells 19.6.1. Validation 19.6.2. Format masks 19.7. Formulas 19.8. Images 19.9. Hyperlinks 19.10. Headers and footers 19.11. Print areas and titles 19.12. Worksheet Commands 19.12.1. Grouping 19.12.2. Page breaks 19.12.3. Merging 19.13. Datatable exporter 19.14. Fonts and layout 19.14.1. Stylesheet links 19.14.2. Fonts 19.14.3. Borders 19.14.4. Background 19.14.5. Column settings 19.14.6. Cell settings 19.14.7. The datatable exporter 19.14.8. Layout examples 19.14.9. Limitations 19.15. Links and further documentation 20. RSS support 20.1. Installation 20.2. Generating feeds 20.3. Feeds 20.4. Entries 20.5. Links and further documentation 21. Email 21.1. Creating a message 21.1.1. Attachments 21.1.2. HTML/Text alternative part 21.1.3. Multiple recipients 21.1.4. Multiple messages 21.1.5. Templating 21.1.6. Internationalisation 21.1.7. Other Headers 21.2. Receiving emails 21.3. Configuration 21.3.1. mailSession 21.4. Meldware 21.5. Tags 22. Asynchronicity and messaging 22.1. Asynchronicity 22.1.1. Asynchronous methods 22.1.2. Asynchronous methods with the Quartz Dispatcher 22.1.3. Asynchronous events 22.1.4. Handling exceptions from asynchronous calls 22.2. Messaging in Seam 22.2.1. Configuration 22.2.2. Sending messages 22.2.3. Receiving messages using a message-driven bean 22.2.4. Receiving messages in the client 23. Caching 23.1. Using Caching in Seam 23.2. Page fragment caching 24. Web Services 24.1. Configuration and Packaging 24.2. Conversational Web Services 24.2.1. A Recommended Strategy 24.3. An example web service 24.4. RESTful HTTP webservices with RESTEasy 24.4.1. RESTEasy configuration and request serving 24.4.2. Resources and providers as Seam components 25. Remoting 25.1. Configuration 25.2. The "Seam" object 25.2.1. A Hello World example 25.2.2. Seam.Component 25.2.3. Seam.Remoting 25.3. Evaluating EL Expressions 25.4. Client Interfaces 25.5. The Context 25.5.1. Setting and reading the Conversation ID 25.5.2. Remote calls within the current conversation scope 25.6. Batch Requests 25.7. Working with Data types 25.7.1. Primitives / Basic Types 25.7.2. JavaBeans 25.7.3. Dates and Times 25.7.4. Enums 25.7.5. Collections 25.8. Debugging 25.9. Handling Exceptions 25.10. The Loading Message 25.10.1. Changing the message 25.10.2. Hiding the loading message 25.10.3. A Custom Loading Indicator 25.11. Controlling what data is returned 25.11.1. Constraining normal fields 25.11.2. Constraining Maps and Collections 25.11.3. Constraining objects of a specific type 25.11.4. Combining Constraints 25.12. JMS Messaging 25.12.1. Configuration 25.12.2. Subscribing to a JMS Topic 25.12.3. Unsubscribing from a Topic 25.12.4. Tuning the Polling Process 26. Seam and the Google Web Toolkit 26.1. Configuration 26.2. Preparing your component 26.3. Hooking up a GWT widget to the Seam component 26.4. GWT Ant Targets 27. Spring Framework integration 27.1. Injecting Seam components into Spring beans 27.2. Injecting Spring beans into Seam components 27.3. Making a Spring bean into a Seam component 27.4. Seam-scoped Spring beans 27.5. Using Spring PlatformTransactionManagement 27.6. Using a Seam Managed Persistence Context in Spring 27.7. Using a Seam Managed Hibernate Session in Spring 27.8. Spring Application Context as a Seam Component 27.9. Using a Spring TaskExecutor for @Asynchronous 28. Hibernate Search 28.1. Introduction 28.2. Configuration 28.3. Usage 29. Configuring Seam and packaging Seam applications 29.1. Basic Seam configuration 29.1.1. Integrating Seam with JSF and your servlet container 29.1.2. Using Facelets 29.1.3. Seam Resource Servlet 29.1.4. Seam servlet filters 29.1.5. Integrating Seam with your EJB container 29.1.6. Don't forget! 29.2. Using Alternate JPA Providers 29.3. Configuring Seam in Java EE 5 29.3.1. Packaging 29.4. Configuring Seam in J2EE 29.4.1. Boostrapping Hibernate in Seam 29.4.2. Boostrapping JPA in Seam 29.4.3. Packaging 29.5. Configuring Seam in Java SE, without JBoss Embedded 29.6. Configuring Seam in Java SE, with JBoss Embedded 29.6.1. Installing Embedded JBoss 29.6.2. Packaging 29.7. Configuring jBPM in Seam 29.7.1. Packaging 29.8. Configuring SFSB and Session Timeouts in JBoss AS 29.9. Running Seam in a Portlet 29.10. Deploying custom resources 30. Seam annotations 30.1. Annotations for component definition 30.2. Annotations for bijection 30.3. Annotations for component lifecycle methods 30.4. Annotations for context demarcation 30.5. Annotations for use with Seam JavaBean components in a J2EE environment 30.6. Annotations for exceptions 30.7. Annotations for Seam Remoting 30.8. Annotations for Seam interceptors 30.9. Annotations for asynchronicity 30.10. Annotations for use with JSF 30.10.1. Annotations for use with dataTable 30.11. Meta-annotations for databinding 30.12. Annotations for packaging 30.13. Annotations for integrating with the servlet container 31. Built-in Seam components 31.1. Context injection components 31.2. Utility components 31.3. Components for internationalization and themes 31.4. Components for controlling conversations 31.5. jBPM-related components 31.6. Security-related components 31.7. JMS-related components 31.8. Mail-related components 31.9. Infrastructural components 31.10. Miscellaneous components 31.11. Special components 32. Seam JSF controls 32.1. Tags 32.1.1. Navigation Controls 32.1.2. Converters and Validators 32.1.3. Formatting 32.1.4. Seam Text 32.1.5. Dropdowns 32.1.6. Other 32.2. Annotations 33. JBoss EL 33.1. Parameterized Expressions 33.1.1. Usage 33.1.2. Limitations and Hints 33.2. Projection 34. Performance Tuning 34.1. Bypassing Interceptors 35. Testing Seam applications 35.1. Unit testing Seam components 35.2. Integration testing Seam components 35.2.1. Using mocks in integration tests 35.3. Integration testing Seam application user interactions 35.3.1. Configuration 35.3.2. Using SeamTest with another test framework 35.3.3. Integration Testing with Mock Data 35.3.4. Integration Testing Seam Mail 36. Seam tools 36.1. jBPM designer and viewer 36.1.1. Business process designer 36.1.2. Pageflow viewer 37. Seam on BEA's Weblogic 37.1. Installation and operation of Weblogic 37.1.1. Installing 10.3 37.1.2. Creating your Weblogic domain 37.1.3. How to Start/Stop/Access your domain 37.1.4. Setting up Weblogic's JSF Support 37.2. The jee5/booking Example 37.2.1. EJB3 Issues with Weblogic 37.2.2. Getting the jee5/booking Working 37.3. The jpa booking example 37.3.1. Building and deploying jpa booking example 37.3.2. What's different with Weblogic 10.x 37.4. Deploying an application created using seam-gen on Weblogic 10.x 37.4.1. Running seam-gen setup 37.4.2. What to change for Weblogic 10.X 37.4.3. Building and Deploying your application 38. Seam on IBM's Websphere 38.1. Websphere environment and deployment information 38.1.1. Installation versions and tips 38.1.2. Required custom properties 38.2. The jee5/booking example 38.2.1. Configuration file changes 38.2.2. Building the jee5/booking example 38.2.3. Deploying the application to Websphere 38.3. The jpa booking example 38.3.1. Building the jpa example 38.3.2. Deploying the jpa example 38.3.3. Whats different for Websphere 6.1 38.4. Deploying an application created using seam-gen on Websphere 6.1.0.13 38.4.1. Running seam-gen Setup 38.4.2. Changes needed for deployment to Websphere 39. Seam on GlassFish application server 39.1. GlassFish environment and deployment information 39.1.1. Installation 39.2. The jee5/booking example 39.2.1. Building the jee5/booking example 39.2.2. Deploying the application to GlassFish 39.3. The jpa booking example 39.3.1. Building the jpa example 39.3.2. Deploying the jpa example 39.3.3. What's different for GlassFish v2 UR2 39.4. Deploying an application generated by seam-gen on GlassFish v2 UR2 39.4.1. Running seam-gen Setup 39.4.2. Changes needed for deployment to GlassFish 40. Dependencies 40.1. JDK Dependencies 40.1.1. Sun's JDK 6 Considerations 40.2. Project Dependencies 40.2.1. Core 40.2.2. RichFaces 40.2.3. Seam Mail 40.2.4. Seam PDF 40.2.5. Seam Microsoft® Excel® 40.2.6. Seam RSS support 40.2.7. JBoss Rules 40.2.8. JBPM 40.2.9. GWT 40.2.10. Spring 40.2.11. Groovy 40.3. Dependency Management using Maven Введение в JBoss Seam Seam is an application framework for Enterprise Java. It is inspired by the following principles: Один тип "сущности" Seam defines a uniform component model for all business logic in your application. A Seam component 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, which is preserved across multiple web requests in a user interaction. There is no distinction between presentation tier components and business logic components in Seam. You can layer your application according to whatever architecture you devise, rather than being forced to shoehorn your application logic into an unnatural layering scheme forced upon you by whatever combination of stovepipe frameworks you're using today. Unlike plain Java EE or J2EE components, Seam components may simultaneously access state associated with the web request and state held in transactional resources (without the need to propagate web request state manually via method parameters). You might object that the application layering imposed upon you by the old J2EE platform was a Good Thing. Well, nothing stops you creating an equivalent layered architecture using Seam—the difference is that you get to architect your own application and decide what the layers are and how they work together. Integrate JSF with EJB 3.0 JSF and EJB 3.0 are two of the best new features of Java EE 5. EJB3 is a brand new component model for server side business and persistence logic. Meanwhile, JSF is a great component model for the presentation tier. Unfortunately, neither component model is able to solve all problems in computing by itself. Indeed, JSF and EJB3 work best used together. But the 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 extension points to allow extension and integration with other frameworks. Seam unifies the component models of JSF and EJB3, eliminating glue code, and letting the developer think about the business problem. It is possible to write Seam applications where "everything" is an EJB. This may come as a surprise if you're used to thinking of EJBs as coarse-grained, so-called "heavyweight" objects. However, version 3.0 has completely changed the nature of EJB from the point of view of the developer. An EJB is a fine-grained object—nothing more complex than an annotated JavaBean. Seam even encourages you to use session beans as 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 any Java class may be a Seam component, and Seam provides all the functionality that you expect from a "lightweight" container, and more, for any component, EJB or otherwise. Integrated AJAX Seam supports the best open source JSF-based AJAX solutions: JBoss RichFaces and ICEfaces. These solutions let you add AJAX capability to your user interface without the need to write any JavaScript code. Alternatively, Seam provides a built-in JavaScript remoting layer that lets you call components asynchronously from client-side JavaScript without the need for an intermediate action layer. You can 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 state management, which ensures that many concurrent fine-grained, asynchronous AJAX requests are handled safely and efficiently on the server side. Business process as a first class construct Optionally, Seam provides transparent business process management via jBPM. You won't believe how easy it is to implement complex workflows, collaboration and and task management using jBPM and Seam. Seam even allows you to define presentation tier pageflow using the same language (jPDL) that jBPM uses for business process definition. JSF provides an incredibly rich event model for the presentation tier. Seam enhances this model by exposing 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 We're all used to the concept of declarative transaction management and declarative security from the early days of EJB. EJB 3.0 even introduces declarative persistence context management. These are three examples of a broader problem of managing state that is associated with a particular context, while ensuring that all needed cleanup occurs when the context ends. Seam takes the concept of declarative state management much further and applies it to application state. Traditionally, J2EE applications implement state management manually, by getting and setting servlet session and request attributes. This approach to state management is the source of many bugs and memory leaks when applications fail to clean up session attributes, or when session data associated with different workflows collides in a multi-window application. Seam has the potential to almost entirely eliminate this class of bugs. Declarative application state management is made possible by the richness of the context model defined 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 meaningful from the point of view of the business logic. You'll be amazed at how many things become easier once you start using conversations. Have you ever suffered pain dealing with lazy association fetching in an ORM solution like Hibernate or JPA? Seam's conversation-scoped persistence contexts mean you'll rarely have to see a LazyInitializationException. Have you ever had problems with the refresh button? The back button? With duplicate form submission? With propagating messages across a post-then-redirect? Seam's conversation management solves these problems without you even needing to really think about them. They're all symptoms of the broken state management architecture that has 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 in numerous so-called "lightweight containers". Most of these containers emphasize injection of components that implement stateless services. Even when injection of stateful components is supported (such as in JSF), it is virtually useless for handling application state because the scope of the stateful component cannot be defined with sufficient flexibility, and because components belonging to wider 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 a mechanism for aliasing contextual variables (names in the various contexts bound to the current thread) to attributes of the component. Bijection allows auto-assembly of stateful components by the container. It even allows a component to safely and easily manipulate the value of a context variable, 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 a different, safely isolated, conversation. Applications may even take advantage of workspace management, allowing the user to switch between conversations (workspaces) in a single browser tab. Seam provides not only correct multi-window operation, but also multi-window-like operation in a single window! Prefer annotations to XML Traditionally, the Java community has been in a state of deep confusion about precisely what kinds of meta-information counts as configuration. J2EE and popular "lightweight" containers have provided XML-based deployment descriptors both for things which are truly configurable between different deployments of the system, and for any other kinds or declaration which can not easily be expressed in Java. Java 5 annotations changed all this. EJB 3.0 embraces annotations and "configuration by exception" as the easiest way to provide information to the container in a declarative form. Unfortunately, JSF is still heavily dependent on verbose XML configuration files. Seam extends the annotations provided by EJB 3.0 with a set of annotations for declarative state management and declarative context demarcation. This lets you eliminate the noisy JSF managed bean declarations and reduce the required XML to just that 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 complex applications, unit testing alone is insufficient. Integration testing has traditionally been a messy and difficult task for Java web applications. Therefore, Seam provides for testability of Seam applications as a core feature of the framework. You can easily write JUnit or TestNG tests that reproduce a whole interaction with a user, exercising all components of the system apart from the view (the JSP or Facelets page). You can run these tests directly inside your IDE, where Seam will automatically deploy EJB components using JBoss Embedded. The specs ain't perfect We think the latest incarnation of Java EE is great. But we know it's never going to be perfect. Where there are holes in the specifications (for example, limitations in the JSF lifecycle for GET requests), Seam fixes them. And the authors of Seam are working with the JCP expert groups to make 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 Java objects. And then they leave you hanging. A truly complete web application framework should address problems like persistence, concurrency, asynchronicity, state management, security, email, messaging, PDF and chart generation, workflow, wikitext rendering, webservices, caching and more. Once you scratch the surface of Seam, you'll be amazed at how many problems become simpler... Seam integrates JPA and Hibernate3 for persistence, the EJB Timer Service and Quartz for lightweight asychronicity, jBPM for workflow, JBoss Rules for business rules, Meldware Mail for email, Hibernate Search and Lucene for full text search, JMS for messaging and JBoss Cache for page fragment caching. Seam layers an innovative rule-based security framework over JAAS and JBoss Rules. There's even JSF tag libraries for rendering PDF, outgoing email, charts and wikitext. Seam components may be called synchronously as a Web Service, asynchronously from client-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 environment supports EJB 3.0, great! If it doesn't, no problem, you can use Seam's built-in transaction management with JPA or Hibernate3 for persistence. Or, you can deploy JBoss Embedded in Tomcat, and get full support for EJB 3.0. [Image] It turns out that the combination of Seam, JSF and EJB3 is the simplest way to write a complex web application in Java. You won't believe how little code is required! 1. Contribute to Seam Visit SeamFramework.org to find out how to contribute to Seam! Chapter 1. Seam Tutorial 1.1. Using the Seam examples 1.1.1. Running the examples on JBoss AS 1.1.2. Running the examples on Tomcat 1.1.3. Running the example tests 1.2. Your first Seam application: the registration example 1.2.1. Understanding the code 1.2.2. How it works 1.3. Clickable lists in Seam: the messages example 1.3.1. Understanding the code 1.3.2. How it works 1.4. Seam and jBPM: the todo list example 1.4.1. Understanding the code 1.4.2. How it works 1.5. Seam pageflow: the numberguess example 1.5.1. Understanding the code 1.5.2. How it works 1.6. A complete Seam application: the Hotel Booking example 1.6.1. Introduction 1.6.2. Overview of the booking example 1.6.3. Understanding Seam conversations 1.6.4. The Seam Debug Page 1.7. Nested conversations: extending the Hotel Booking example 1.7.1. Introduction 1.7.2. Understanding Nested Conversations 1.8. A complete application featuring Seam and jBPM: the DVD Store example 1.9. Bookmarkable URLs with the Blog example 1.9.1. Using "pull"-style MVC 1.9.2. Bookmarkable search results page 1.9.3. Using "push"-style MVC in a RESTful application 1.1. Using the Seam examples Seam provides a number of example applications demonstrating how to use the various features of Seam. This tutorial will guide you through a few of those examples to help you get started learning Seam. The Seam examples are located in the examples subdirectory of the Seam distribution. The registration example, which will be the first example we look at, is in the examples/registration directory. Each example has the same directory structure: * The view directory contains view-related files such as web page templates, images and stylesheets. * The resources directory contains deployment descriptors and other configuration files. * The src directory contains the application source code. The example applications run both on JBoss AS and Tomcat with no additional configuration. The following sections will explain the procedure in both cases. Note that all the examples are built and run from the Ant build.xml, so you'll need a recent version of Ant installed before you get started. 1.1.1. Running the examples on JBoss AS The examples are configured for use on JBoss 4.2. You'll need to set jboss.home, in the shared build.properties file in the root folder of your Seam installation, to the location of your JBoss AS installation. Once you've set the location of JBoss AS and started the application server, you can build and deploy any example by typing ant explode in the the directory for that example. Any example that is packaged as an EAR deploys to a URL like /seam-example, where example is the name of the example folder, with one exception. If the example folder begins with seam, the prefix "seam" is ommitted. For instance, if JBoss AS is running on port 8080, the URL for the registration example is http://localhost:8080/seam-registration/, whereas the URL for the seamspace example is http://localhost:8080/seam-space/. If, on the other hand, the example gets packaged as a WAR, then it deploys to a URL like /jboss-seam-example. Most of the examples can be deployed as a WAR to Tomcat with Embedded JBoss by typing ant tomcat.deploy. Several of the examples can only be deployed as a WAR. Those examples are groovybooking, hibernate, jpa, and spring. 1.1.2. Running the examples on Tomcat The examples are also configured for use on Tomcat 6.0. You will need to follow the instructions in Section 29.6.1, “Installing Embedded JBoss” for installing JBoss Embedded on Tomcat 6.0. JBoss Embedded is only required to run the Seam demos that use EJB3 components on Tomcat. There are also examples of non-EJB3 applications that can be run on Tomcat without the use of JBoss Embedded. You'll need to set tomcat.home, in the shared build.properties file in the root folder of your Seam installation, to the location of your Tomcat installation. make sure you set the location of your Tomcat. You'll need to use a different Ant target when using Tomcat. Use ant tomcat.deploy in example subdirectory to build and deploy any example for Tomcat. On Tomcat, the examples deploy to URLs like /jboss-seam-example, so for the registration example the URL would be http://localhost:8080/jboss-seam-registration/. The same is true for examples that deploy as a WAR, as mentioned in the previous section. 1.1.3. Running the example tests Most of the examples come with a suite of TestNG integration tests. The easiest way to run the tests is to run ant test. It is also possible to run the tests inside your IDE using the TestNG plugin. Consult the readme.txt in the examples directory of the Seam distribution for more information. 1.2. Your first Seam application: the registration example The registration example is a simple application that lets a new user store his username, real name and password in the database. The example isn't intended to show off all of the cool functionality of Seam. However, it demonstrates the use of an EJB3 session bean as a JSF action listener, and basic configuration of Seam. We'll go slowly, since we realize you might not yet be familiar with EJB 3.0. The start page displays a very basic form with three input fields. Try filling them in and then submitting the form. This will save a user object in the database. [Image] 1.2.1. Understanding the code The example is implemented with two Facelets templates, 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 We need an EJB entity bean for user data. This class defines persistence and validation declaratively, via annotations. It also needs some extra annotations that define the class as a Seam component. Example 1.1. User.java (1)@Entity (2)@Name("user") (3)@Scope(SESSION) (4)@Table(name="users") public class User implements Serializable { private static final long serialVersionUID = 1881413500711441951L; (5) 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; } (6) public User() {} (7) @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; } (8) @Id @NotNull @Length(min=5, max=15) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } 1 The EJB3 standard @Entity annotation indicates that the User class is an entity bean. 2 A Seam component needs a component name specified by the @Name annotation. This name must be unique within the Seam application. When JSF asks Seam to resolve a context variable with a name that 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. 3 Whenever Seam instantiates a component, it binds the new instance to a context variable in the component's default context. The default context is specified using the @Scope annotation. The User bean is a session scoped component. 4 The EJB standard @Table annotation indicates that the User class is mapped to the users table. 5 name, password and username are the persistent attributes of the entity bean. All of our persistent attributes define accessor methods. These are needed when this component is used by JSF in the render response and update model values phases. 6 An empty constructor is both required by both the EJB specification and by Seam. 7 The @NotNull and @Length annotations are part of the Hibernate Validator framework. Seam integrates Hibernate Validator and lets you use it for data validation (even if you are not using Hibernate for persistence). 8 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. These annotations establish that this class is a Seam component. We'll see below that the properties of our User class are bound directly to JSF components and are populated by JSF during the update model values phase. We don't need any tedious glue code to copy data 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 this component 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 you like). We have exactly one JSF action in our application, and one session bean method attached to it. In this case, 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! Example 1.2. RegisterAction.java @Stateless (1) @Name("register") public class RegisterAction implements Register { @In private Use(2)r user; @PersistenceContext private Ent(3)ityManager em; @Logger private Log(4) log; public String register() { (5) List existing = em.createQuery( "select username from User where username = #{user.username}") .getR(6)esultList(); if (existing.size()==0) { em.persist(user); log.info("Registered new user #{user.username}"); retur(7)n "/registered.xhtml"; } (8) else { FacesMessages.instance().add("User #{user.username} already exists"); retur(9)n null; } } } 1 The EJB @Stateless annotation marks this class as a stateless session bean. 2 The @In annotation marks an attribute of the bean as injected by Seam. In this case, the attribute is injected from a context variable named user (the instance variable name). 3 The EJB standard @PersistenceContext annotation is used to inject the EJB3 entity manager. 4 The Seam @Logger annotation is used to inject the component's Log instance. 5 The action listener method uses the standard EJB3 EntityManager API to interact with the database, and returns the JSF outcome. Note that, since this is a session bean, a transaction is automatically begun when the register() method is called, and committed when it completes. 6 Notice that Seam lets you use a JSF EL expression inside EJB-QL. Under the covers, this results in an ordinary JPA setParameter() call on the standard JPA Query object. Nice, huh? 7 The Log API lets us easily display templated log messages which can also make use of JSF EL expressions. 8 JSF action listener methods return a string-valued outcome that determines what page will be displayed next. A null outcome (or a void action listener method) redisplays the previous page. In plain JSF, it is normal to always use a JSF navigation rule to determine the JSF view id from the outcome. For complex application this indirection is useful and a good practice. However, for very simple examples like this one, Seam lets you use the JSF view id as the outcome, eliminating the requirement for a navigation rule. Note that when you use a view id as an outcome, Seam always performs a browser redirect. 9 Seam provides a number of built-in components to help solve common problems. The FacesMessages component makes it easy to display templated error or success messages. (As of Seam 2.1, you can use StatusMessages instead to remove the semantic dependency on JSF). Built-in Seam components may be obtained by injection, or by calling the instance() method on the class of the built-in component. Note that we did not explicitly specify a @Scope this time. Each Seam component type has a default scope if not explicitly specified. For stateless session beans, the default scope is the stateless context, which is the only sensible value. Our session bean action listener performs the business and persistence logic for our mini-application. In more complex applications, we might need require a separate service layer. This is easy to achieve with Seam, but it's overkill for most web applications. Seam does not force you into any particular strategy for application layering, allowing your application to be as simple, or as complex, as you want. Note that in this simple application, we've actually made it far more complex than it needs to be. If we had used the Seam application framework controllers, we would have eliminated all of our application code. However, then we wouldn't have had much of an application to explain. 1.2.1.3. The session bean local interface: Register.java Naturally, our session bean needs a local interface. Example 1.3. Register.java @Local public interface Register { public String register(); } That's the end of the Java code. Now we'll look at the view. 1.2.1.4. 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. Example 1.4. register.xhtml Register New User Username: Real Name: Password: The only thing here that is specific to Seam is the tag. This JSF component tells JSF to validate all the contained input fields against the Hibernate Validator annotations specified on the entity bean. Example 1.5. registered.xhtml Successfully Registered New User Welcome, #{user.name}, you are successfully registered as #{user.username}. This is a simple Facelets page using some inline EL. There's nothing specific to Seam here. 1.2.1.5. The Seam component deployment descriptor: components.xml Since this is the first Seam app we've seen, we'll take a look at the deployment descriptors. Before we get into them, it is worth noting that Seam strongly values minimal configuration. These configuration files will be created for you when you create a Seam application. You'll never need to touch most of these files. We're presenting them now only to help you understand what all the pieces in the example are doing. If you've used many Java frameworks before, you'll be used to having to declare all your component classes in some kind of XML file that gradually grows more and more unmanageable as your project matures. You'll be relieved to know that Seam does not require that application components be accompanied by XML. Most Seam applications require a very small amount of XML that does not grow very much as the project gets bigger. Nevertheless, it is often useful to be able to provide for some external configuration of some components (particularly the components built in to Seam). You have a couple of options here, but the most 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 components in JNDI: Example 1.6. components.xml 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 the correct JNDI pattern in when we deploy the application, which it reads from the components.properties file. You learn more about how this process works in Section 5.2, “Configuring components via components.xml”. 1.2.1.6. The web deployment description: web.xml The presentation layer for our mini-application will be deployed in a WAR. So we'll need a web deployment descriptor. Example 1.7. web.xml org.jboss.seam.servlet.SeamListener javax.faces.DEFAULT_SUFFIX .xhtml Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet *.seam 10 This web.xml file configures Seam and JSF. The configuration you see here is pretty much identical in all Seam applications. 1.2.1.7. The JSF configration: 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 to use Facelets as its templating engine. Example 1.8. faces-config.xml com.sun.facelets.FaceletViewHandler Note that we don't need any JSF managed bean declarations! Our managed beans are annotated Seam components. In Seam applications, the faces-config.xml is used much less often than in plain JSF. Here, we are simply using it to enable Facelets as the view handler instead of JSP. In fact, once you have all the basic descriptors set up, the only XML you need to write as you add new functionality to a Seam application is orchestration: navigation rules or jBPM process definitions. Seam's stand is 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 in our action code. 1.2.1.8. The EJB deployment descriptor: ejb-jar.xml The ejb-jar.xml file integrates Seam with EJB3, by attaching the SeamInterceptor to all session beans in the archive. org.jboss.seam.ejb.SeamInterceptor * org.jboss.seam.ejb.SeamInterceptor 1.2.1.9. The EJB persistence deployment descriptor: persistence.xml The persistence.xml file tells the EJB persistence provider where to find the datasource, and contains some vendor-specific settings. In this case, enables automatic schema export at startup time. org.hibernate.ejb.HibernatePersistence java:/DefaultDS 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. Example 1.9. registration application Seam Registration jboss-seam-registration.war /seam-registration jboss-seam-registration.jar jboss-seam.jar jboss-el.jar This deployment descriptor links modules in the enterprise archive and binds the web application to the 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 no value already bound to that name (in any Seam context), Seam instantiates the user component, and returns 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 redisplays the page. Otherwise, JSF binds the form input values to properties of the User entity bean. Next, JSF asks Seam to resolve the variable named register. Seam uses the JNDI pattern mentioned earlier to locate the stateless session bean, wraps it as a Seam component, and returns it. Seam then presents this component to JSF and JSF invokes the register() action listener method. But Seam is not done yet. Seam intercepts the method call and injects the User entity from the Seam session context, before allowing the invocation to continue. The register() method checks if a user with the entered username already exists. If so, an error message is queued with the FacesMessages component, and a null outcome is returned, causing a page redisplay. The FacesMessages component interpolates the JSF expression embedded in the message string and adds a JSF FacesMessage to the view. If no user with that username exists, the "/registered.xhtml" outcome triggers a browser redirect to the registered.xhtml page. When JSF comes to render the page, it asks Seam to resolve the variable 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 that Seam provides special functionality on top of JSF to make it easier to query data using EJB-QL or HQL and display it as a clickable list using a JSF . The messages example demonstrates this functionality. [Image] 1.3.1. Understanding the code The message list example has one entity bean, Message, one session bean, MessageListBean and one 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 whether the message has been read: Example 1.10. Message.java @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; } @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; } } 1.3.1.2. The stateful session bean: MessageManagerBean.java Just like in the previous example, we have a session bean, MessageManagerBean, which defines the action listener methods for the two buttons on our form. One of the buttons selects a message from the list, and displays that message. The other button deletes a message. So far, this is not so different to the previous example. But MessageManagerBean is also responsible for fetching the list of messages the first time we navigate to the message list page. There are various ways the user could navigate to the page, and not all of them are preceded by a JSF action—the user might have bookmarked the page, for example. So the job of fetching the message list takes place in a Seam factory method, instead of in an action listener method. We want to cache the list of messages in memory between server requests, so we will make this a stateful session bean. Example 1.11. MessageManagerBean.java @Stateful @Scope(SESSION) @Name("messageManager") public class MessageManagerBean implements Serializable, MessageManager { @DataModel private Lis(1)t messageList; @DataModelSelection @Out(requir(2)ed=false) private Mes(3)sage message; @PersistenceContext(type=EXTENDED) private Ent(4)ityManager em; @Factory("messageList") public void(5) findMessages() { messageList = em.createQuery("select msg from Message msg order by msg.datetime desc") .getResultList(); } public void select() { (6) message.setRead(true); } public void delete() { (7) messageList.remove(message); em.remove(message); message=null; } @Remove public void(8) destroy() {} } 1 The @DataModel annotation exposes an attibute of type java.util.List to the JSF page as an instance of javax.faces.model.DataModel. This allows us to use the list in a JSF with clickable links for each row. In this case, the DataModel is made available in a session context variable named messageList. 2 The @DataModelSelection annotation tells Seam to inject the List element that corresponded to the clicked link. 3 The @Out annotation then exposes the selected value directly to the page. So ever time a row of the clickable list is selected, the Message is injected to the attribute of the stateful bean, and the subsequently outjected to the event context variable named message. 4 This stateful bean has an EJB3 extended persistence context. The messages retrieved in the query remain in the managed state as long as the bean exists, so any subsequent method calls to the stateful bean can update them without needing to make any explicit call to the EntityManager. 5 The first time we navigate to the JSP page, there will be no value in the messageList context variable. The @Factory annotation tells Seam to create an instance of MessageManagerBean and invoke the findMessages() method to initialize the value. We call findMessages() a factory method for messages. 6 The select() action listener method marks the selected Message as read, and updates it in the database. 7 The delete() action listener method removes the selected Message from the database. 8 All stateful session bean Seam components must have a method with no parameters marked @Remove that Seam uses to remove the stateful bean when the Seam context ends, and clean up any server-side state. Note that this is a session-scoped Seam component. It is associated with the user login session, and all requests from a login session share the same instance of the component. (In Seam applications, we usually 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. Example 1.12. MessageManager.java @Local public interface MessageManager { public void findMessages(); public void select(); public void delete(); public void destroy(); } 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 go straight to the JSP. 1.3.1.4. The view: messages.jsp The JSP page is a straightforward use of the JSF component. Again, nothing specific to Seam. Example 1.13. messages.jsp <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> Messages

Message List

1.3.2. How it works The first time we navigate to the messages.jsp page, the page will try to resolve the messageList context variable. 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 being outjected. This DataModel provides the row data needed for rendering the . When the user clicks the , JSF calls the select() action listener. Seam intercepts this call and injects the selected row data into the message attribute of the messageManager component. The action listener fires, marking the selected Message as read. At the end of the call, Seam outjects the selected Message to the context variable named message. Next, the EJB container commits the transaction, and the change to the Message is flushed to the database. Finally, the page is re-rendered, redisplaying the message list, and displaying the selected message below it. If the user clicks the , JSF calls the delete() action listener. Seam intercepts this 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() on the EntityManager. At the end of the call, Seam refreshes the messageList context variable and clears the context variable named message. The EJB container commits the transaction, and deletes the Message from the database. Finally, the page is re-rendered, redisplaying the message list. 1.4. Seam and jBPM: the todo list example jBPM provides sophisticated functionality for workflow and task management. To get a small taste of how jBPM integrates with Seam, we'll show you a simple "todo list" application. Since managing lists of tasks is such core functionality for jBPM, there is hardly any Java code at all in this example. [Image] 1.4.1. Understanding the code The center of this example is the jBPM process definition. There are also two JSPs and two trivial JavaBeans (There was no reason to use session beans, since they do not access the database, or have any other transactional behavior). Let's start with the process definition: Example 1.14. todo.jpdl.xml 1 The node represents the logical start of the process. When the process starts, it immediately transitions to the todo node. 2 The node represents a wait state, where business process execution pauses, waiting for one or more tasks to be performed. 3 The element defines a task to be performed by a user. Since there is only one task defined on this node, when it is complete, execution resumes, and we transition to the end state. The task gets its description from a Seam component named todoList (one of the JavaBeans). 4 Tasks need to be assigned to a user or group of users when they are created. In this case, the task is assigned to the current user, which we get from a built-in Seam component named actor. Any Seam component may be used to perform task assignment. 5 The node defines the logical end of the business process. When execution reaches this node, the process instance is destroyed. If we view this process definition using the process definition editor provided by JBossIDE, this is what it looks like: [Image] This document defines our business process as a graph of nodes. This is the most trivial possible business process: there is one task to be performed, and when that task is complete, the business process ends. The first JavaBean handles the login screen login.jsp. Its job is just to initialize the jBPM actor id using the actor component. In a real application, it would also need to authenticate the user. Example 1.15. Login.java @Name("login") public class Login { @In private Actor actor; private String user; public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String login() { actor.setId(user); return "/todo.jsp"; } } Here we see the use of @In to inject the built-in Actor component. The JSP itself is trivial: Example 1.16. login.jsp <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> Login

Login

The second JavaBean is responsible for starting business process instances, and ending tasks. Example 1.17. TodoList.java @Name("todoList") public class TodoList { private String description; public Stri(1)ng getDescription() { return description; } public void setDescription(String description) { this.description = description; } (2) @CreateProcess(definition="todo") public void createTodo() {} (3) @StartTask @EndTask public void done() {} } 1 The description property accepts user input form the JSP page, and exposes it to the process definition, allowing the task description to be set. 2 The Seam @CreateProcess annotation creates a new jBPM process instance for the named process definition. 3 The Seam @StartTask annotation starts work on a task. The @EndTask ends the task, and allows the business 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 core of the application is in todo.jsp: Example 1.18. todo.jsp <%@ 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" %> Todo List

Todo List

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. Example 1.19. todo.jsp
...
Each element of the list is an instance of the jBPM class TaskInstance. The following code simply displays the interesting properties of each task in the list. For the description, priority and due date, we use input controls, to allow the user to update these values. This button ends the task by calling the action method annotated @StartTask @EndTask. It passes the task id to Seam as a request parameter: Note that this is using a Seam 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 jBPM will 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.
1.4.2. How it works After logging in, todo.jsp uses the taskInstanceList component to display a table of outstanding todo items for a the current user. Initially there are none. It also presents a form to enter a new entry. When the user types the todo item and hits the "Create New Item" button, #{todoList.createTodo} is called. This starts the todo process, as defined in todo.jpdl.xml. The process instance is created, starting in the start state and immediately transition to the todo state, where a new task is created. The task description is set based on the user's input, which was saved to #{todoList.description}. Then, the task is assigned to the current user, which was stored in the seam actor component. Note that in this example, the process has no extra process state. All the state in this example is stored in the task definition. The process and task information is stored in the database at the end of the request. When todo.jsp is redisplayed, taskInstanceList now finds the task that was just created. The task is shown in an h:dataTable. The internal state of the task is displayed in each column: #{task.description}, #{task.priority}, #{task.dueDate}, etc... These fields can all be edited and saved back to the database. Each todo item also has "Done" button, which calls #{todoList.done}. The todoList component knows which task the button is for because each s:button specificies taskInstance="#{task}", referring to the task for that particular line of of the table. The @StartTast and @EndTask annotations cause seam to make the task active and immediately complete the task. The original process then transitions into the done state, according to the process definition, where it ends. The state of the task and process are both updated in the database. When todo.jsp is displayed again, the now-completed task is no longer displayed in the taskInstanceList, since that component only display active tasks for the user. 1.5. Seam pageflow: the numberguess example For Seam applications with relatively freeform (ad hoc) navigation, JSF/Seam navigation rules are a perfectly good way to define the page flow. For applications with a more constrained style of navigation, especially for user interfaces which are more stateful, navigation rules make it difficult to really understand the flow of the system. To understand the flow, you need to piece it together from the view pages, the actions and the navigation rules. Seam allows you to use a jPDL process definition to define pageflow. The simple number guessing example shows how this is done. [Image] 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: Example 1.20. pageflow.jpdl.xml (4) 1 The element defines a wait state where the system displays a particular JSF view and waits for user input. The view-id is the same JSF view id used in plain JSF navigation rules. The redirect attribute tells Seam to use post-then-redirect when navigating to the page. (This results in friendly browser URLs.) 2 The element names a JSF outcome. The transition is triggered when a JSF action results in that outcome. Execution will then proceed to the next node of the pageflow graph, after invocation of any jBPM transition actions. 3 A transition is just like a JSF action, except that it occurs when a jBPM transition occurs. The transition action can invoke any Seam component. 4 A node branches the pageflow, and determines the next node to execute by evaluating a JSF EL expression. Here is what the pageflow looks like in the JBoss Developer Studio pageflow editor: [Image] 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: Example 1.21. numberGuess.jspx < Guess a number... 7.11.3. RichFaces Ajax RichFaces Ajax is the AJAX library most commonly used with Seam, and provides all the controls discussed above: * eventsQueue — provide a queue in which events are placed. All events are queued and requests are sent to the server serially. This is useful if the request can to the server can take some time to execute (e.g. heavy computation, retrieving information from a slow source) as the server isn't flooded. * ignoreDupResponses — ignore the response produced by the request if a more recent 'similar' request is already in the queue. ignoreDupResponses="true" does not cancel the the processing of the request on the server side — just prevents unnecessary updates on the client side. This option should be used with care with Seam's conversations as it allows multiple concurrent requests to be made. * requestDelay — defines the time (in ms.) that the request will be remain on the queue. If the request has not been processed by after this time the request will be sent (regardless of whether a response has been received) or discarded (if there is a more recent similar event on the queue). This option should be used with care with Seam's conversations as it allows multiple concurrent requests to be made. You need to be sure that the delay you set (in combination with the concurrent request timeout) is longer than the action will take to execute. * — Polls the server, and rerenders an area as needed Chapter 8. Pageflows and business processes 8.1. Pageflow in Seam 8.1.1. The two navigation models 8.1.2. Seam and the back button 8.2. Using jPDL pageflows 8.2.1. Installing pageflows 8.2.2. Starting pageflows 8.2.3. Page nodes and transitions 8.2.4. Controlling the flow 8.2.5. Ending the flow 8.2.6. Pageflow composition 8.3. Business process management in Seam 8.4. Using jPDL business process definitions 8.4.1. Installing process definitions 8.4.2. Initializing actor ids 8.4.3. Initiating a business process 8.4.4. Task assignment 8.4.5. Task lists 8.4.6. Performing a task JBoss jBPM is a business process management engine for any Java SE or EE environment. jBPM lets you 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 called jPDL, and may be edited and visualised graphically using an eclipse plugin. jPDL is an extensible language, and is suitable for a range of problems, from defining web application page flow, to traditional workflow management, all the way up to orchestration of services in a SOA environment. Seam applications use jBPM for two different problems: * Defining the pageflow involved in complex user interactions. A jPDL process definition defines the page flow for a single conversation. A Seam conversation is considered to be a relatively short-running interaction with a single user. * Defining the overarching business process. The business process may span multiple conversations with multiple users. Its state is persistent in the jBPM database, so it is considered long-running. Coordination of the activities of multiple users is a much more complex problem than scripting an interaction with a single user, so jBPM offers sophisticated facilities for task management and dealing with multiple concurrent paths of execution. Don't get these two things confused! They operate at very different levels or granularity. Pageflow, conversation and task all refer to a single interaction with a single user. A business process spans many tasks. Futhermore, the two applications of jBPM are totally orthogonal. You can use them together or independently or not at all. You don't have to know jDPL to use Seam. If you're perfectly happy defining pageflow using JSF or Seam navigation rules, and if your application is more data-driven that process-driven, you probably don't need jBPM. But we're finding that thinking of user interaction in terms of a well-defined graphical representation is helping us build more robust applications. 8.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. Very complex applications will use both models in different places. Each model has its strengths and weaknesses! 8.1.1. The two navigation models The stateless model defines a mapping from a set of named, logical outcomes of an event directly to the resulting page of the view. The navigation rules are entirely oblivious to any state held by the application other than what page was the source of the event. This means that your action listener methods must sometimes make decisions about the page flow, since only they have access to the current state of the application. Here is an example page flow definition using JSF navigation rules: /numberGuess.jsp guess /numberGuess.jsp win /win.jsp lose /lose.jsp 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 listener methods: public String guess() { if (guess==randomNumber) return "/win.jsp"; if (++guessCount==maxGuesses) return "/lose.jsp"; return null; } Note that this results in a redirect. You can even specify parameters to be used in the redirect: public String search() { return "/searchResults.jsp?searchPattern=#{searchAction.searchPattern}"; } The stateful model defines a set of transitions between a set of named, logical application states. In this model, 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: [Image] There are two things we notice immediately here: * The JSF/Seam navigation rules are much simpler. (However, this obscures the fact that the underlying Java code is more complex.) * The jPDL makes the user interaction immediately understandable, without us needing to even look 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 hoc model which is suitable to relatively unconstrained, freeform navigation where the user decides where he/she wants to go next, not the application. The stateful/stateless navigation distinction is quite similar to the traditional view of modal/modeless interaction. 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 the order in which your users are going to want to do things! However, there is no doubt that the stateful model has its place. The biggest contrast between the two models is the back-button behavior. 8.1.2. Seam and the back button When JSF or Seam navigation rules are used, Seam lets the user freely navigate via the back, forward and refresh buttons. It is the responsibility of the application to ensure that conversational state remains internally consistent when this occurs. Experience with the combination of web application frameworks like Struts or WebWork - that do not support a conversational model - and stateless component models like EJB stateless session beans or the Spring framework has taught many developers that this is close to impossible to do! However, our experience is that in the context of Seam, where there is a well-defined conversational model, backed by stateful session beans, it is actually 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 for freeform navigation to be almost always desirable. In this case, the no-conversation-view-id declaration goes in pages.xml. It tells Seam to redirect to a different page if a request originates from a page rendered during a conversation, and that conversation no longer exists: On the other hand, in the stateful model, backbuttoning is interpreted as an undefined transition back to a previous state. Since the stateful model enforces a defined set of transitions from the current state, back buttoning is by default disallowed in the stateful model! Seam transparently detects the use of the back button, and blocks any attempt to perform an action from a previous, "stale" page, and simply redirects the user to the "current" page (and displays a faces message). Whether you consider this a feature or a limitation of the stateful model depends upon your point of view: as an application developer, it is a feature; as a user, it might be frustrating! You can enable backbutton navigation from a particular 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 a pageflow, 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 to prefer one model over the other. 8.2. Using jPDL pageflows 8.2.1. Installing pageflows We need to install the Seam jBPM-related components, and place the pageflow definitions (using the standard .jpdl.xml extension) inside a Seam archive (an archive which contains a seam.properties file): We can also explicitly tell Seam where to find our pageflow definition. We specify this in components.xml: pageflow.jpdl.xml 8.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: @Begin(pageflow="numberguess") public void begin() { ... } 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, and use a 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 action listener determines which is the first page to be rendered. In this case, we use a as the first node in the pageflow, and declare a transition for each possible outcome: ... 8.2.3. Page nodes and transitions Each node represents a state where the system is waiting for user input: The view-id is the JSF view id. The element has the same effect as in a JSF navigation rule: namely, a post-then-redirect behavior, to overcome problems with the browser's refresh button. (Note that Seam propagates conversation contexts over these browser redirects. So there is no need for a Ruby on Rails style "flash" construct in Seam!) The transition name is the name of a JSF outcome triggered by clicking a command button or command link in numberGuess.jsp. When the transition is triggered by clicking this button, jBPM will activate the transition action by calling the guess() method of the numberGuess component. Notice that the syntax used for specifying actions in the jPDL is just a familiar JSF EL expression, and that the transition action handler is just a method of a Seam component in the current Seam contexts. So we have exactly the same event model for jBPM events that we already have for JSF events! (The One Kind of Stuff principle.) In the case of a null outcome (for example, a command button with no action defined), Seam will signal the transition with no name if one exists, or else simply redisplay the page if all transitions have names. 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 will determine the transition to be taken: However, this is considered an inferior style, since it moves responsibility for controlling the flow out of the pageflow definition and back into the other components. It is much better to centralize this concern in the pageflow itself. 8.2.4. Controlling the flow Usually, we don't need the more powerful features of jPDL when defining pageflows. We do need the node, however: A decision is made by evaluating a JSF EL expression in the Seam contexts. 8.2.5. Ending the flow We end the conversation using or @End. (In fact, for readability, use of both is encouraged.) Optionally, we can end a task, specify a jBPM transition name. In this case, Seam will signal the end of the current task in the overarching business process. 8.2.6. Pageflow composition It is possible to compose pageflows and have one pageflow pause pause while another pageflow executes. The node pauses the outer pageflow, and begins execution of a named pageflow: The inner flow begins executing at a node. When it reaches an node, execution of the inner flow ends, and execution of the outer flow resumes with the transition defined by the element. 8.3. Business process management in Seam A business process is a well-defined set of tasks that must be performed by users or software systems according to well-defined rules about who can perform a task, and when it should be performed. Seam's jBPM integration makes it easy to display lists of tasks to users and let them manage their tasks. Seam also lets the application store state associated with the business process in the BUSINESS_PROCESS context, 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 nodes, we have nodes. In a long-running business process, the wait states are where the system is waiting for some user to log in and perform a task. [Image] It is perfectly possible that we might have both jPDL business process definitions and jPDL pageflow definitions in the same project. If so, the relationship between the two is that a single in a business process corresponds to a whole pageflow 8.4. Using jPDL business process definitions 8.4.1. Installing process definitions We need to install jBPM, and tell it where to find the business process definitions: todo.jpdl.xml As jBPM processes are persistent across application restarts, when using Seam in a production environment you won't want to install the process definition every time the application starts. Therefore, in a production environment, you'll need to deploy the process to jBPM outside of Seam. In other words, only install process definitions from components.xml when developing your application. 8.4.2. Initializing actor ids We always need to know what user is currently logged in. jBPM "knows" users by their actor id and group actor ids. We specify the current actor ids using the built in Seam component named actor: @In Actor actor; public String login() { ... actor.setId( user.getUserName() ); actor.getGroupActorIds().addAll( user.getGroupNames() ); ... } 8.4.3. Initiating a business process To initiate a business process instance, we use the @CreateProcess annotation: @CreateProcess(definition="todo") public void createTodo() { ... } Alternatively we can initiate a business process using pages.xml: 8.4.4. Task assignment When a process reaches a task node, task instances are created. These must be assigned to users or user 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: 8.4.5. Task lists Several built-in Seam components make it easy to display task lists. The pooledTaskInstanceList is a list of pooled tasks that users may assign to themselves: Description Note that instead of we could have used a plain JSF : 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 to the current user: Description 8.4.6. Performing a task To begin work on a task, we use either @StartTask or @BeginTask on the listener method: @StartTask public String start() { ... } 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 the overarching business process. Work done by this conversation has access to state held in the business process context. If we end the conversation using @EndTask, Seam will signal the completion of the task: @EndTask(transition="completed") public String completed() { ... } 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 more complex 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 features that jBPM provides for managing complex business processes. Chapter 9. Seam and Object/Relational Mapping 9.1. Introduction 9.2. Seam managed transactions 9.2.1. Disabling Seam-managed transactions 9.2.2. Configuring a Seam transaction manager 9.2.3. Transaction synchronization 9.3. Seam-managed persistence contexts 9.3.1. Using a Seam-managed persistence context with JPA 9.3.2. Using a Seam-managed Hibernate session 9.3.3. Seam-managed persistence contexts and atomic conversations 9.4. Using the JPA "delegate" 9.5. Using EL in EJB-QL/HQL 9.6. Using Hibernate filters Seam 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-management architecture allows the most sophisticated ORM integration of any web application framework. 9.1. Introduction Seam grew out of the frustration of the Hibernate team with the statelessness typical of the previous generation of Java application architectures. The state management architecture of Seam was originally designed to solve problems relating to persistence—in particular problems associated with optimistic transaction processing. Scalable online applications always use optimistic transactions. An atomic (database/JTA) level transaction should not span a user interaction unless the application is designed to support only a very small number of concurrent clients. But almost all interesting work involves first displaying data to a user, and then, slightly later, updating the same data. So Hibernate was designed to support the idea of a persistence context which spanned an optimistic transaction. Unfortunately, the so-called "stateless" architectures that preceded Seam and EJB 3.0 had no construct for representing an optimistic transaction. So, instead, these architectures provided persistence contexts scoped to the atomic transaction. Of course, this resulted in many problems for users, and is the cause of the number one user complaint about Hibernate: the dreaded LazyInitializationException. What we need is a construct 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 session bean) with an extended persistence context scoped to the lifetime of the component. This is a partial solution 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 optimistic transaction is possible, but tricky. Seam solves the first problem by providing conversations, and stateful session bean components scoped to the conversation. (Most conversations actually represent optimistic transactions in the data layer.) This is sufficient for many simple applications (such as the Seam booking demo) where persistence context propagation is not needed. For more complex applications, with many loosly-interacting components in each conversation, propagation of the persistence context across components becomes an important issue. So Seam extends the persistence context management model of EJB 3.0, to provide conversation-scoped extended persistence contexts. 9.2. Seam managed transactions EJB session beans feature declarative transaction management. The EJB container is able to start a transaction transparently when the bean is invoked, and end it when the invocation ends. If we write a session bean method that acts as a JSF action listener, we can do all the work associated with that action in one transaction, and be sure that it is committed or rolled back when we finish processing the action. 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 access for a request from a single method call to a session bean. * The request might require processing by several loosly-coupled components, each of which is called independently from the web layer. It is common to see several or even many calls per request from the web layer to EJB components in Seam. * Rendering of the view might require lazy fetching of associations. The more transactions per request, the more likely we are to encounter atomicity and isolation problems when our application is processing many concurrent requests. Certainly, all write operations should occur in the same transaction! Hibernate users developed the "open session in view" pattern to work around this problem. In the Hibernate community, "open session in view" was historically even more important because frameworks like Spring use transaction-scoped persistence contexts. So rendering the view would cause LazyInitializationExceptions when unfetched associations were accessed. This pattern is usually implemented as a single transaction which spans the entire request. There are several problems with this implementation, the most serious being that we can never be sure that a transaction is successful until we commit it—but by the time the "open session in view" transaction is committed, the view is fully rendered, and the rendered response may already have been flushed to the client. How can we notify the user that their transaction was unsuccessful? Seam solves both the transaction isolation problem and the association fetching problem, while working 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 the transaction * 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 request vaues phase) until the end of the invoke application phase; the second spans the render response phase In the next section, we'll tell you how to set up a conversation-scope persistence context. But first we 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 to use Seam transaction management even when you're 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're using EJB 3.0 container-managed persistence contexts. But it is especially useful if you use Seam outside a Java EE 5 environment, or in any other case where you would use a Seam-managed persistence context. 9.2.1. Disabling Seam-managed transactions Seam transaction management is enabled by default for all JSF requests. If you want to disable this feature, you can do it in components.xml: 9.2.2. Configuring a Seam transaction manager Seam provides a transaction management abstraction for beginning, committing, rolling back, and synchronizing with a transaction. By default Seam uses a JTA transaction component that integrates with Container Managed and programmatic EJB transactions. If you are working in a Java EE 5 environment, you should install the EJB synchronization component in components.xml: However, if you are working in a non EE 5 container, Seam will try auto detect the transaction synchronization mechanism to use. However, if Seam is unable to detect the correct transaction synchronization to use, you may find you need configure one of the following: * JPA RESOURCE_LOCAL transactions with the javax.persistence.EntityTransaction interface. EntityTransaction begins the transaction at the beginning of the apply request values phase. * Hibernate managed transactions with the org.hibernate.Transaction interface. HibernateTransaction begins the transaction at the beginning of the apply request values phase. * Spring managed transactions with the org.springframework.transaction.PlatformTransactionManager interface. The Spring PlatformTransactionManagement manager may begin the transaction at the beginning of the apply request values phase if the userConversationContext attribute is set. * Explicitly disable Seam managed transactions Configure JPA RESOURCE_LOCAL transaction management by adding the following to your components.xml where #{em} is the name of the persistence:managed-persistence-context component. If your managed persistence context is named entityManager, you can opt to leave out the entity-manager attribute. (see 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-session component. If your managed hibernate session is named session, you can opt to leave out the session attribute. (see Seam-managed persistence contexts ) To explicitly disable Seam managed transactions declare the following in your components.xml: For configuring Spring managed transactions see using Spring PlatformTransactionManagement . 9.2.3. Transaction synchronization Transaction synchronization provides callbacks for transaction related events such as beforeCompletion() and afterCompletion(). By default, Seam uses it's own transaction synchronization component which requires explicit use of the Seam transaction component when committing a transaction to ensure synchronization callbacks are correctly executed. If in a Java EE 5 environment the component should be be declared in components.xml to ensure that Seam synchronization callbacks are correctly called if the container commits a transaction outside of Seam's knowledge. 9.3. Seam-managed persistence contexts If you're using Seam outside of a Java EE 5 environment, you can't rely upon the container to manage the persistence context lifecycle for you. Even if you are in an EE 5 environment, you might have a complex application with many loosly coupled components that collaborate together in the scope of a single conversation, and in this case you might find that propagation of the persistence context between component is tricky and error-prone. In either case, you'll need to use a managed persistence context (for JPA) or a managed session (for Hibernate) in your components. A Seam-managed persistence context is just a built-in Seam component 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 able to 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 persisence contexts, without the need to replicate any persistence context state between nodes. (We hope to fix this oversight in the next revision of the EJB spec.) 9.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 that manages 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. In JBoss, you can do this by adding the following property setting to persistence.xml. Now we can have our EntityManager injected using: @In EntityManager bookingDatabase; 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 the conversation, it will be propagated to methods marked REQUIRES_NEW. Therefore, if you mark a method REQUIRES_NEW then you should access the entity manager using @PersistenceContext. 9.3.2. Using a Seam-managed Hibernate session Seam-managed Hibernate sessions are similar. In components.xml: Where java:/bookingSessionFactory is the name of the session factory specified in hibernate.cfg.xml. true after_statement org.hibernate.transaction.JBossTransactionManagerLookup org.hibernate.transaction.JTATransactionFactory java:/bookingDatasource ... Note that Seam does not flush the session, so you should always enable hibernate.transaction.flush_before_completion to ensure that the session is automatically flushed before the JTA transaction commits. We can now have a managed Hibernate Session injected into our JavaBean components using the following code: @In Session bookingDatabase; 9.3.3. Seam-managed persistence contexts and atomic conversations Persistence contexts scoped to the conversation allows you to program optimistic transactions that span multiple requests to the server without the need to use the merge() operation , without the need to 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 achieved via use of optimistic locking. Fortunately, both Hibernate and EJB 3.0 make it very easy to use optimistic locking, by providing the @Version annotation. By default, the persistence context is flushed (synchronized with the database) at the end of each transaction. This is sometimes the desired behavior. But very often, we would prefer that all changes are held in memory and only written to the database when the conversation ends successfully. This allows for truly atomic conversations. As the result of a truly stupid and shortsighted decision by certain non-JBoss, non-Sun and non-Sybase members of the EJB 3.0 expert group, there is currently 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 by the 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 works only when Hibernate is the underlying persistence provider, but we plan to support other equivalent vendor extensions. @In EntityManager em; //a Seam-managed persistence context @Begin(flushMode=MANUAL) public void beginClaimWizard() { claim = em.find(Claim.class, claimId); } Now, the claim object remains managed by the persistence context for the rest ot the conversation. We can make changes to the claim: public void addPartyToClaim() { Party party = ....; claim.addParty(party); } But these changes will not be flushed to the database until we explicitly force the flush to occur: @End public void commitClaim() { em.flush(); } Of course, you could set the flushMode to MANUAL from pages.xml, for example in a navigation rule: You can set any Seam Managed Persistence Context to use manual flush mode: 9.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 you must use a different JPA provider see Using Alternate JPA Providers. But regardless of whether you're using Hibernate (genius!) or something else (masochist, or just not very bright), you'll almost certainly want to use the delegate in your Seam components from time to time. One approach would be the following: @In EntityManager entityManager; @Create public void init() { ( (Session) entityManager.getDelegate() ).enableFilter("currentVersions"); } But typecasts are unquestionably the ugliest syntax in the Java language, so most people avoid them whenever possible. Here's a different way to get at the delegate. First, add the following line to components.xml: Now we can inject the session directly: @In Session session; @Create public void init() { session.enableFilter("currentVersions"); } 9.5. Using EL in EJB-QL/HQL Seam proxies the EntityManager or Session object whenever you use a Seam-managed persistence 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: User user = em.createQuery("from User where username=#{user.username}") .getSingleResult(); is equivalent to: User user = em.createQuery("from User where username=:username") .setParameter("username", user.getUsername()) .getSingleResult(); Of course, you should never, ever write it like this: User user = em.createQuery("from User where username=" + user.getUsername()) //BAD! .getSingleResult(); (It is inefficient and vulnerable to SQL injection attacks.) 9.6. Using Hibernate filters The coolest, and most unique, feature of Hibernate is filters. Filters let you provide a restricted view of the data in the database. You can find out more about filters in the Hibernate documentation. But we thought we'd mention an easy way to incorporate filters into a Seam application, one that works especially well with the Seam Application Framework. Seam-managed persistence contexts may have a list of filters defined, which will be enabled whenever an EntityManager or Hibernate Session is first created. (Of course, they may only be used when Hibernate is the underlying persistence provider.) region regionCode #{region.code} current date #{currentDate} #{regionFilter} #{currentFilter} Chapter 10. JSF form validation in Seam In plain JSF, validation is defined in the view:
Country:
Zip code:
In practice, this approach usually violates DRY, since most "validation" actually enforces constraints that are part of the data model, and exist all the way down to the database schema definition. Seam provides support for model-based constraints defined using Hibernate Validator. Let's start by defining our constraints, on our Location class: 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; } } Well, that's a decent first cut, but in practice it might be more elegant to use custom constraints instead of the ones built into Hibernate Validator: public class Location { private String country; private String zip; @NotNull @Country 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; } } Whichever route we take, we no longer need to specify the type of validation to be used in the JSF page. Instead, we can use to validate against the constraint defined on the model object.
Country:
Zip code:
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 JSF validation architecture. This approach defines constraints on the model, and presents constraint violations in the view—a significantly better design. However, it is not much less verbose than what we started with, so let's try :
Country:
Zip code:
This tag simply adds an to every input in the form. For a large form, it can save a lot of typing! Now we need to do something about displaying feedback to the user when validation fails. Currently we are displaying all messages at the top of the form. In order for the user to correlate the message with an input, you need to define a label using the standard label attribute on the input component. You can then inject this value into the message string using the placeholder {0} (the first and only parameter passed to a JSF message for a Hiberate Validator restriction). See the internationalization section for more information regarding where to define these messages. validator.length={0} length must be between {min} and {max} What we would really like to do, though, is display the message next to the field with the error (this is possible in plain JSF), highlight the field and label (this is not possible) and, for good measure, display some image next to the field (also not possible). We also want to display a little colored asterisk next to the label for each required form field. Using this approach, the identifying label is not necessary. That's quite a lot of functionality we need for each field of our form. We wouldn't want to have to specify higlighting and the layout of the image, message and input field for every field on the form. So, instead, we'll specify the common layout in a facelets template:
*
We can include this template for each of our form fields using . Country: Zip code: Finally, we can use RichFaces Ajax to display validation messages as the user is navigating around the form: Country: Zip code: It's better style to define explicit ids for important controls on the page, especially if you want to do automated testing for the UI, using some toolkit like Selenium. If you don't provide explicit ids, JSF will generate them, but the generated values will change if you change anything on the page. Country: Zip code: And what if you want to specify a different message to be displayed when validation fails? You can use the Seam message bundle (and all it's goodies like el expressions inside the message, and per-view message bundles) with the Hibernate Validator: 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} Chapter 11. Groovy integration 11.1. Groovy introduction 11.2. Writing Seam applications in Groovy 11.2.1. Writing Groovy components 11.2.2. seam-gen 11.3. Deployment 11.3.1. Deploying Groovy code 11.3.2. Native .groovy file deployment at development time 11.3.3. seam-gen One aspect of JBoss Seam is its RAD (Rapid Application Development) capability. While not synonymous with RAD, one interesting tool in this space is dynamic languages. Until recently, choosing a dynamic language was required choosing a completely different development platform (a development platform with a set of APIs and a runtime so great that you would no longer want to use you old legacy Java [sic] APIs anymore, which would be lucky because you would be forced to use those proprietary APIs anyway). 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 integrating both static and dynamic languages. JBoss Seam lets the application developer use the best tool for the task, without context switching. Writing dynamic Seam components is exactly like writing regular Seam components. You use the same annotations, the same APIs, the same everything. 11.1. Groovy introduction Groovy is an agile dynamic language based on the Java language but with additional features inspired by 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 very smooth * Groovy objects are Java objects, and Groovy classes are Java classes: Groovy integrates smoothly with existing Java libraries and frameworks. TODO: write a quick overview of the Groovy syntax add-on 11.2. Writing Seam applications in Groovy There is not much to say about it. Since a Groovy object is a Java object, you can virtually write any Seam component, or any class for what it worth, in Groovy and deploy it. You can also mix Groovy classes and Java classes in the same application. 11.2.1. Writing Groovy components As you should have noticed by now, Seam uses annotations heavily. Be sure to use Groovy 1.1 or above for annotation support. Here are some example of groovy code used in a Seam application. 11.2.1.1. Entity @Entity @Name("hotel") class Hotel implements Serializable { @Id @GeneratedValue Long id @Length(max=50) @NotNull String name @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})" } } Groovy natively support the notion of properties (getter/setter), so there is no need to explicitly write verbose 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 of syntactic sugar makes the entity code very concise. 11.2.1.2. Seam component Writing Seam components in Groovy is in no way different than in Java: annotations are used to mark the class as a Seam component. @Scope(ScopeType.SESSION) @Name("bookingList") class BookingListAction implements Serializable { @In EntityManager em @In User user @DataModel List 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() { 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]) } } 11.2.2. seam-gen Seam gen has a transparent integration with Groovy. You can write Groovy code in seam-gen backed projects without any additional infrastructure requirement. When writing a Groovy entity, simply place your .groovy files in src/main. Unsurprisingly, when writing an action, simply place your .groovy files in src/hot. 11.3. Deployment Deploying Groovy classes is very much like deploying Java classes (surprisingly, no need to write nor comply 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 redeploy JavaBeans Seam component classes without having to restart the application, saving a lot of time in the development / test cycle. The same support is provided for GroovyBeans Seam components when the .groovy files are deployed. 11.3.1. Deploying Groovy code A Groovy class is a Java class, with a bytecode representation just like a Java class. To deploy, a Groovy entity, a Groovy Session bean or a Groovy Seam component, a compilation step is necessary. A common approach is to use the groovyc ant task. Once compiles, a Groovy class is in no way different than a Java class and the application server will treat them equally. Note that this allow a seamless mix of Groovy and Java code. 11.3.2. Native .groovy file deployment at development time JBoss Seam natively supports the deployment of .groovy files (ie without compilation) in incremental hotdeployment mode (development only). This enables a very fast edit/test cycle. To set up .groovy deployments, follow the configuration at Section 2.8, “Seam and incremental hot deployment” and deploy your Groovy code (.groovy files) into the WEB-INF/dev directory. The GroovyBean components will be picked up incrementally with no need to restart the application (and obviously not the application server either). Be aware that the native .groovy file deployment suffers the same limitations as the regular Seam hotdeployment: * 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 * Seam debug mode must be enabled 11.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 of type WAR, Java and Groovy classes in src/hot will automatically be candidate for the incremental hot deployment. If you are in production mode, the Groovy files will simply be compiled before deployment. You will find a live example of the Booking demo written completely in Groovy and supporting incremental hot deployment in examples/groovybooking. Chapter 12. Writing your presentation layer using Apache Wicket 12.1. Adding Seam to your wicket application 12.1.1. Bijection 12.1.2. Orchestration 12.2. Setting up your project 12.2.1. Defining the Application Seam supports Wicket as an alternative presentation layer to JSF. Take a look at the wicket example in Seam which shows the Booking Example ported to Wicket. Note Wicket support is new to Seam, so some features which are available in JSF are not yet available when you use Wicket (e.g. pageflow). You'll also notice that the documentation is very JSF-centric and needs reorganization to reflect the first class support for Wicket. 12.1. Adding Seam to your wicket application The features added to your Wicket application can be split into two categories: bijection and orchestration; these are discussed in detail below. Extensive use of inner classes is common when building Wicket applications, with the component tree being built in the constructor. Seam fully supports the use of annotation based control in inner classes and constructors (unlike regular Seam components). Annotations are processed after any call to a superclass. This mean's that any injected attributes cannot be passed as an argument in a call to this() or super(). Note We are working to improve this. When a method is called in an inner class, bijection occurs for any class which encloses it. This allows you to place your bijected variables in the outer class, and refer to them in any inner class. 12.1.1. Bijection A Seam enabled Wicket application has full access to the all the standard Seam contexts (EVENT, CONVERSATION, SESSION, APPLICATION and BUSINESS_PROCESS). To access Seam component's from Wicket, you just need to inject it using @In: @In(create=true) private HotelBooking hotelBooking; Tip As your Wicket class isn't a full Seam component, there is no need to annotate it @Name. You can also outject an object into the Seam contexts from a Wicket component: @Out(scope=ScopeType.EVENT, required=false) private String verify; TODO Make this more use case driven 12.1.2. Orchestration You can secure a Wicket component by using the @Restrict annotation. This can be placed on the outer component or any inner components. If @Restrict is specified, the component will automatically be restricted to logged in users. You can optionally use an EL expression in the value attribute to specify a restriction to be applied. For more refer to the Chapter 15, Security. For example: @Restrict public class Main extends WebPage { ... Tip Seam will automatically apply the restriction to any nested classes. You can demarcate conversations from within a Wicket component through the use of @Begin and @End. The semantics for these annotations are the same as when used in a Seam component. You can place @Begin and @End on any method. Note The deprecated ifOutcome attribute is not supported. For example: item.add(new Link("viewHotel") { @Override @Begin public void onClick() { hotelBooking.selectHotel(hotel); setResponsePage(org.jboss.seam.example.wicket.Hotel.class); } }; You may have pages in your application which can only be accessed when the user has a long-running conversation active. To enforce this you can use the @NoConversationPage annotation: @Restrict @NoConversationPage(Main.class) public class Hotel extends WebPage { If you want to further decouple your application classes, you can use Seam events. Of course, you can raise an event using Events.instance().raiseEvent("foo"). Alternatively, you can annotate a method @RaiseEvent("foo"); if the method returns a non-null outcome without exception, the event will be raised. You can also control tasks and processes in Wicket classes through the use of @CreateProcess, @ResumeTask, @BeginTask, @EndTask, @StartTask and @Transition. TODO - Implement BPM control - JBSEAM-3194 12.2. Setting up your project Seam needs to instrument the bytecode of your Wicket classes to be able to intercept the annotations you use. Seam provides two ways to do this.The first is to place your classes in WEB-INF/wicket. Seam will look for classes placed in this directory at startup and instrument them. An alternative approach, which can be used alongside the first, is to use an ant task for instrumention. Seam provides such a task; it is packaged in jboss-seam-wicket-ant.jar , and can be used in the following manner: Then have ant copy the instrumented classes in ${build.instrumented} into WEB-INF/classes. If you want to hot deploy the Wicket components, you can copy the instrumented classes to WEB-INF/dev; if you use hot deploy, make sure that your WicketApplication class is also hot-deployed. Upon a reload of hot-deployed classes, the entire WicketApplication instance has to be re-initialized, in order to pick up new references to the classes of mounted pages. 12.2.1. Defining the Application A Wicket web application which uses Seam should use SeamWebApplication as the base class; this creates hooks into the Wicket lifecycle allowing Seam to automagically propagate the conversation as needed. It also adds status messages to the page. For example: The SeamAuthorizationStrategy delegates authorization to Seam Security, allowing the use of @Restrict on Wicket components. SeamWebApplication installs the authorization strategy for you. You can specify the login page by implementing the getLoginPage() method. You'll also need to set the home page of the application by implementing the getHomePage() method. public class WicketBookingApplication extends SeamWebApplication { @Override public Class getHomePage() { return Home.class; } @Override protected Class getLoginPage() { return Home.class; } } Seam automatically installs the Wicket filter for you (ensuring that it is inserted in the correct place for you). But you still need to tell Wicket which WebApplication class to use: #{param.personId} If that looks a bit too much like "programming in XML" for your taste, you can use extension instead: @Name("personHome") public class PersonHome extends EntityHome { @In EntityManager personDatabase; public EntityManager getEntityManager() { return personDatabase; } } The second approach has one huge advantage: you can easily add extra functionality, and override the built-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 not have to be, they can be plain JavaBean components if you prefer.) If you are using JBoss AS, you'll need 4.2.2.GA or later: @Stateful @Name("personHome") public class PersonHome extends EntityHome implements LocalPersonHome { } You can also make your classes stateless session beans. In this case you must use injection to provide the persistence context, even if it is called entityManager: @Stateless @Name("personHome") public class PersonHome extends EntityHome implements LocalPersonHome { @In EntityManager entityManager; public EntityManager getPersistenceContext() { entityManager; } } At this time, the Seam Application Framework provides four main built-in components: EntityHome and HibernateEntityHome for CRUD, along with EntityQuery and HibernateEntityQuery for queries. The Home and Query components are written so that they can function with a scope of session, event or conversation. Which scope you use depends upon the state model you wish to use in your application. 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 our trusty Person class: @Entity public class Person { @Id private Long id; private String firstName; private String lastName; private Country nationality; //getters and setters... } We can define a personHome component either via configuration: Or via extension: @Name("personHome") public class PersonHome extends EntityHome {} 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 the identifier of the object you are interested in, using the setId() method. We can use a Home directly from a JSF page, for example:

Create Person

First name:
Last name:
Usually, it is much nicer to be able to refer to the Person merely as person, so let's make that possible by adding a line to components.xml: (If we are using configuration.) Or by adding a @Factory method to PersonHome: @Name("personHome") public class PersonHome extends EntityHome { @Factory("person") public Person initPerson() { return getInstance(); } } (If we are using extension.) This change simplifies our JSF page to the following:

Create Person

First name:
Last name:
Well, that lets us create new Person entries. Yes, that is all the code that is required! Now, 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 entry identifier to the PersonHome. Page parameters are a great way to do that: Now we can add the extra operations to our JSF page:

First name:
Last name:
When we link to the page with no request parameters, the page will be displayed as a "Create Person" page. 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, via configuration: #{country} Or by extension: @Name("personHome") public class PersonHome extends EntityHome { @In Country country; @Factory("person") public Person initPerson() { return getInstance(); } protected Person createInstance() { return new Person(country); } } 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. @Name("personHome") public class PersonHome extends EntityHome { @In Country country; @Factory("person") public Person initPerson() { return getInstance(); } protected Person createInstance() { return new Person(country); } public void migrate() { getInstance().setCountry(country); update(); } } The Home object raises an org.jboss.seam.afterTransactionSuccess event when a transaction succeeds (a call to persist(), update() or remove() succeeds). By observing this event we can refresh our queries when the underlying entities are changed. If we only want to refresh certain queries when a particular entity is persited, updated or removed we can observe the org.jboss.seam.afterTransactionSuccess. event (where is the name of the entity). The Home object automatically displays faces messages when an operation is successful. To customize these messages we can, again, use configuration: New person #{person.firstName} #{person.lastName} created Person #{person.firstName} #{person.lastName} deleted Person #{person.firstName} #{person.lastName} updated #{country} Or extension: @Name("personHome") public class PersonHome extends EntityHome { @In Country country; @Factory("person") public Person initPerson() { return getInstance(); } protected Person createInstance() { return new Person(country); } protected String getCreatedMessage() { return createValueExpression("New person #{person.firstName} #{person.lastName} created"); } protected String getUpdatedMessage() { return createValueExpression("Person #{person.firstName} #{person.lastName} updated"); } protected String getDeletedMessage() { return createValueExpression("Person #{person.firstName} #{person.lastName} deleted"); } } But the best way to specify the messages is to put them in a resource bundle known to Seam (the bundle named messages, by default). Person_created=New person #{person.firstName} #{person.lastName} created Person_deleted=Person #{person.firstName} #{person.lastName} deleted Person_updated=Person #{person.firstName} #{person.lastName} updated This enables internationalization, and keeps your code and configuration clean of presentation concerns. The final step is to add validation functionality to the page, using and , but I'll leave that for you to figure out. 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:

List of people

We probably need to support pagination: We'll use a page parameter to determine the page to display: The JSF code for a pagination control is a bit verbose, but manageable:

Search for people

Real search screens let the user enter a bunch of optional search criteria to narrow the list of results returned. The Query object lets you specify optional "restrictions" to support this important usecase: lower(firstName) like lower( concat(#{examplePerson.firstName},'%') ) lower(lastName) like lower( concat(#{examplePerson.lastName},'%') ) Notice the use of an "example" object.

Search for people

First name:
Last name:
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 don't work well with join fetch queries - the use of pagination with these queries is not recomended, and you'll have to implement your own method of calculating the total number of results (by overriding getCountEjbql(). The examples in this section have all shown reuse by configuration. However, reuse by extension is equally possible for Query objects. 13.4. Controller objects A totally optional part of the Seam Application Framework is the class Controller and its subclasses EntityController HibernateEntityController and BusinessProcessController. These classes provide nothing more than some convenience methods for access to commonly used built-in components and methods of built-in components. They help save a few keystrokes (characters can add up!) and provide a great launchpad 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; } } } As you can see, its not an earthshattering improvement... Chapter 14. Seam and JBoss Rules 14.1. Installing rules 14.2. Using rules from a Seam component 14.3. Using rules from a jBPM process definition Seam makes it easy to call JBoss Rules (Drools) rulebases from Seam components or jBPM process definitions. 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 the classpath. You can install this component via components.xml: policyPricingRules.drl 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 will need to install multiple rule bases in a rule-driven application. If you want to use a Drools DSL, you alse need to specify the DSL definition: policyPricingRules.drl In most rules-driven applications, rules need to be dynamically deployable, so a production application will want to use a Drools RuleAgent to manage the RuleBase. The RuleAgent can connect to a Drools rule server (BRMS) or hot deploy rules packages from a local file repository. The RulesAgent-managed RuleBase is also configurable in components.xml: The properties file contains properties specific to the RulesAgent. Here is an example configuration file from the Drools example distribution. newInstance=true url=http://localhost:8080/drools-jbrms/org.drools.brms.JBRMS/package/org.acme.insurance/fmeyer localCacheDir=/Users/fernandomeyer/projects/jbossrules/drools-examples/drools-examples-brms/cache poll=30 name=insuranceconfig It is also possible to configure the options on the component directly, bypassing the configuration file. 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: @In WorkingMemory policyPricingWorkingMemory; @In Policy policy; @In Customer customer; public void pricePolicy() throws FactException { policyPricingWorkingMemory.assertObject(policy); policyPricingWorkingMemory.assertObject(customer); policyPricingWorkingMemory.fireAllRules(); } 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. orderApprovalRulesWorkingMemory #{customer} #{order} #{order.lineItems} shippingRulesWorkingMemory #{customer} #{order} #{order.lineItems} The element specifies EL expressions that return an object or collection of objects to be asserted as facts into the WorkingMemory. There is also support for using Drools for jBPM task assignments: orderApprovalRulesWorkingMemory #{actor} #{customer} #{order} #{order.lineItems} 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 perform assignments should set the actor id using the Assignable. 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 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 Note You can find out more about Drools at http://www.drools.org Caution Seam comes with enough of Drools' dependencies to implement some simple rules. If you want to add extra capabilities to Drools you should download the full distribution and add in extra dependencies as needed. Tip Drools comes with MVEL compiled for Java 1.4, which is compatible with Java 1.4, Java 5 and Java 6. You may want to change your MVEL jar with one compiled for the version of Java you are using Chapter 15. Security 15.1. Overview 15.2. Disabling Security 15.3. Authentication 15.3.1. Configuring an Authenticator component 15.3.2. Writing an authentication method 15.3.3. Writing a login form 15.3.4. Configuration Summary 15.3.5. Remember Me 15.3.6. Handling Security Exceptions 15.3.7. Login Redirection 15.3.8. HTTP Authentication 15.3.9. Advanced Authentication Features 15.4. Identity Management 15.4.1. Configuring IdentityManager 15.4.2. JpaIdentityStore 15.4.3. LdapIdentityStore 15.4.4. Writing your own IdentityStore 15.4.5. Authentication with Identity Management 15.4.6. Using IdentityManager 15.5. Error Messages 15.6. Authorization 15.6.1. Core concepts 15.6.2. Securing components 15.6.3. Security in the user interface 15.6.4. Securing pages 15.6.5. Securing Entities 15.6.6. Typesafe Permission Annotations 15.6.7. Typesafe Role Annotations 15.6.8. The Permission Authorization Model 15.6.9. RuleBasedPermissionResolver 15.6.10. PersistentPermissionResolver 15.7. Permission Management 15.7.1. PermissionManager 15.7.2. Permission checks for PermissionManager operations 15.8. SSL Security 15.8.1. Overriding the default ports 15.9. CAPTCHA 15.9.1. Configuring the CAPTCHA Servlet 15.9.2. Adding a CAPTCHA to a form 15.9.3. Customising the CAPTCHA algorithm 15.10. Security Events 15.11. Run As 15.12. Extending the Identity component 15.13. OpenID 15.13.1. Configuring OpenID 15.13.2. Presenting an OpenIdDLogin form 15.13.3. Logging in immediately 15.13.4. Deferring login 15.13.5. Logging out 15.1. Overview The Seam Security API provides a multitude of security-related features for your Seam-based application, covering such areas as: * Authentication - an extensible, JAAS-based authentication layer that allows users to authenticate against any security provider. * Identity Management - an API for managing a Seam application's users and roles at runtime. * Authorization - an extremely comprehensive authorization framework, supporting user roles, persistent and rule-based permissions, and a pluggable permission resolver for easily implementing customised security logic. * Permission Management - a set of built-in Seam components to allow easy management of an application's security policy. * CAPTCHA support - to assist in the prevention of automated software/scripts abusing your Seam-based site. * And much more This chapter will cover each of these features in detail. 15.2. Disabling Security In some situations it may be necessary to disable Seam Security, for instances during unit tests or because you are using a different approach to security, such as native JAAS. Simply call the static method Identity.setSecurityEnabled(false) to disable the security infrastructure. Of course, it's not very convenient to have to call a static method when you want to configure the application, so as an alternative you can control this setting in components.xml: * Entity Security * Hibernate Security Interceptor * Seam Security Interceptor * Page restrictions * Servlet API security integration Assuming you are planning to take advantage of what Seam Security has to offer, the rest of this chapter documents the plethora of options you have for giving your user an identity in the eyes of the security model (authentication) and locking down the application by establishing constraints (authorization). Let's begin with the task of authentication since that's the foundation of any security model. 15.3. Authentication The authentication features provided by Seam Security are built upon JAAS (Java Authentication and Authorization Service), and as such provide a robust and highly configurable API for handling user authentication. However, for less complex authentication requirements Seam offers a much more simplified method of authentication that hides the complexity of JAAS. 15.3.1. Configuring an Authenticator component Note If you use Seam's Identity Management features (discussed later in this chapter) then it is not necessary to create an authenticator component (and you can skip this section). The simplified authentication method provided by Seam uses a built-in JAAS login module, SeamLoginModule, which delegates authentication to one of your own Seam components. This login module is already configured inside Seam as part of a default application policy and as such does not require any additional configuration files. It allows you to write an authentication method using the entity classes that are provided by your own application, or alternatively to authenticate with some other third party provider. Configuring this simplified form of authentication requires the identity component to be configured in components.xml: The EL expression #{authenticator.authenticate} is a method binding that indicates the authenticate method of the authenticator component will be used to authenticate the user. 15.3.2. Writing an authentication method The authenticate-method property specified for identity in components.xml specifies which method will be used by SeamLoginModule to authenticate users. This method takes no parameters, and is expected to return a boolean, which indicates whether authentication is successful or not. The user's username and password can be obtained from Credentials.getUsername() and Credentials.getPassword(), respectively (you can get a reference to the credentials component via Identity.instance().getCredentials()). Any roles that the user is a member of should be assigned using Identity.addRole(). Here's a complete example of an authentication method inside a POJO component: @Name("authenticator") public class Authenticator { @In EntityManager entityManager; @In Credentials credentials; @In Identity identity; public boolean authenticate() { try { User user = (User) entityManager.createQuery( "from User where username = :username and password = :password") .setParameter("username", credentials.getUsername()) .setParameter("password", credentials.getPassword()) .getSingleResult(); if (user.getRoles() != null) { for (UserRole mr : user.getRoles()) identity.addRole(mr.getName()); } return true; } catch (NoResultException ex) { return false; } } } In the above example, both User and UserRole are application-specific entity beans. The roles parameter is populated with the roles that the user is a member of, which should be added to the Set as literal string values, e.g. "admin", "user". In this case, if the user record is not found and a NoResultException thrown, the authentication method returns false to indicate the authentication failed. Tip 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 be called 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 should be written by implementing an event observer. See the section on Security Events further down in this chapter for more information about which events are raised by Seam Security. 15.3.2.1. Identity.addRole() The Identity.addRole() method behaves differently depending on whether the current session is authenticated or not. If the session is not authenticated, then addRole() should only be called during the 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 "real" roles, and calling Identity.hasRole() for those roles will then return true. The following sequence diagram represents the list of pre-authenticated roles as a first class object to show more clearly how it fits in to the authentication process. [Image] If the current session is already authenticated, then calling Identity.addRole() will have the expected effect of immediately granting the specified role to the current user. 15.3.2.2. Writing an event observer for security-related events Say for example, that upon a successful login that some user statistics must be updated. This would be done by writing an event observer for the org.jboss.seam.security.loginSuccessful event, like this: @In UserStats userStats; @Observer("org.jboss.seam.security.loginSuccessful") public void updateUserStats() { userStats.setLastLoginDate(new Date()); userStats.incrementLoginCount(); } This observer method can be placed anywhere, even in the Authenticator component itself. You can find more information about security-related events later in this chapter. 15.3.3. Writing a login form The credentials component provides both username and password properties, catering for the most common authentication scenario. These properties can be bound directly to the username and password fields on a login form. Once these properties are set, calling identity.login() will authenticate the user using the provided credentials. Here's an example of a simple login form:
Similarly, logging out the user is done by calling #{identity.logout}. Calling this action will clear the security state of the currently authenticated user, and invalidate the user's session. 15.3.4. 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.3.5. Remember Me Seam Security supports the same kind of "Remember Me" functionality that is commonly encountered in many online web-based applications. It is actually supported in two different "flavours", or modes - the first mode allows the username to be stored in the user's browser as a cookie, and leaves the entering of the password up to the browser (many modern browsers are capable of remembering passwords). The second mode supports the storing of a unique token in a cookie, and allows a user to authenticate automatically upon returning to the site, without having to provide a password. Warning Automatic client authentication with a persistent cookie stored on the client machine is dangerous. While convenient for users, any cross-site scripting security hole in your website would have dramatically more serious effects than usual. Without the authentication cookie, the only cookie to steal for an attacker with XSS is the cookie of the current session of a user. This means the attack only works when the user has an open session - which should be a short timespan. However, it is much more attractive and dangerous if an attacker has the possibility to steal a persistent Remember Me cookie that allows him to login without authentication, at any time. Note that this all depends on how well you protect your website against XSS attacks - it's up to you to make sure that your website is 100% XSS safe - a non-trival achievement for any website that allows user input to be rendered on a page. Browser vendors recognized this issue and introduced a "Remember Passwords" feature - today almost all browsers support this. Here, the browser remembers the login username and password for a particular website and domain, and fills out the login form automatically when you don't have an active session with the website. If you as a website designer then offer a convenient login keyboard shortcut, this approach is almost as convenient as a "Remember Me" cookie and much safer. Some browsers (e.g. Safari on OS X) even store the login form data in the encrypted global operation system keychain. Or, in a networked environment, the keychain can be transported with the user (between laptop and desktop for example), while browser cookies are usually not synchronized. To summarize: While everyone is doing it, persistent "Remember Me" cookies with automatic authentication are a bad practice and should not be used. Cookies that "remember" only the users login name, and fill out the login form with that username as a convenience, are not an issue. To enable the remember me feature for the default (safe, username only) mode, no special configuration is required. In your login form, simply bind the remember me checkbox to rememberMe.enabled, like in the following example:
15.3.5.1. Token-based Remember-me Authentication To use the automatic, token-based mode of the remember me feature, you must first configure a token store. The most common scenario is to store these authentication tokens within a database (which Seam supports), however it is possible to implement your own token store by implementing the org.jboss.seam.security.TokenStore interface. This section will assume you will be using the provided JpaTokenStore implementation to store authentication tokens inside a database table. The first step is to create a new Entity which will contain the tokens. The following example shows a possible structure that you may use: @Entity public class AuthenticationToken implements Serializable { private Integer tokenId; private String username; private String value; @Id @GeneratedValue public Integer getTokenId() { return tokenId; } public void setTokenId(Integer tokenId) { this.tokenId = tokenId; } @TokenUsername public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @TokenValue public String getValue() { return value; } public void setValue(String value) { this.value = value; } } As you can see from this listing, a couple of special annotations, @TokenUsername and @TokenValue are used to configure the username and token properties of the entity. These annotations are required for the entity that will contain the authentication tokens. The next step is to configure JpaTokenStore to use this entity bean to store and retrieve authentication tokens. This is done in components.xml by specifying the token-class attribute: Once this is done, the last thing to do is to configure the RememberMe component in components.xml also. Its mode should be set to autoLogin: That is all that is required - automatic authentication will now occur for users revisiting your site (as long as they check the "remember me" checkbox). To ensure that users are automatically authenticated when returning to the site, the following section should be placed in components.xml: 15.3.6. Handling Security Exceptions To prevent users from receiving the default error page in response to a security error, it's recommended that pages.xml is configured to redirect security errors to a more "pretty" page. The two main types of exceptions thrown by the security API are: * NotLoggedInException - This exception is thrown if the user attempts to access a restricted 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 the necessary privileges. In the case of a NotLoggedInException, it is recommended that the user is redirected to either a login or registration page so that they can log in. For an AuthorizationException, it may be useful to redirect the user to an error page. Here's an example of a pages.xml file that redirects both of these security exceptions: ... You must be logged in to perform this action You do not have the necessary security privileges to perform this action. Most web applications require even more sophisticated handling of login redirection, so Seam includes some special functionality for handling this problem. 15.3.7. Login Redirection You can ask Seam to redirect the user to a login screen when an unauthenticated user tries to access a particular view (or wildcarded view id) as follows: ... Tip This is less of a blunt instrument than the exception handler shown above, but should probably be used in conjunction with it. After the user logs in, we want to automatically send them back where they came from, so they can retry 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 user successfully logging in they will be redirected to the originally requested view, with any page parameters that existed in the original request. Note that login redirection is implemented as a conversation-scoped mechanism, so don't end the conversation in your authenticate() method. 15.3.8. HTTP Authentication Although not recommended for use unless absolutely necessary, Seam provides means for authenticating using either HTTP Basic or HTTP Digest (RFC 2617) methods. To use either form of authentication, the authentication-filter component must be enabled in components.xml: To enable the filter for basic authentication, set auth-type to basic, or for digest authentication, set it 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 presented to the user when they authenticate. 15.3.8.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: 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; } } 15.3.9. Advanced Authentication Features This section explores some of the advanced features provided by the security API for addressing more complex security requirements. 15.3.9.1. Using your container's JAAS configuration If you would rather not use the simplified JAAS configuration provided by the Seam Security API, you may instead delegate to the default system JAAS configuration by providing a jaas-config-name property in components.xml. For example, if you are using JBoss AS and wish to use the other policy (which uses the UsersRolesLoginModule login module provided by JBoss AS), then the entry in components.xml would look like this: Please keep in mind that doing this does not mean that your user will be authenticated in whichever container your Seam application is deployed in. It merely instructs Seam Security to authenticate itself using the configured JAAS security policy. 15.4. Identity Management Identity Management provides a standard API for the management of a Seam application's users and roles, regardless of which identity store (database, LDAP, etc) is used on the backend. At the center of the Identity Management API is the identityManager component, which provides all the methods for creating, modifying and deleting users, granting and revoking roles, changing passwords, enabling and disabling user accounts, authenticating users and listing users and roles. Before it may be used, the identityManager must first be configured with one or more IdentityStores. These components do the actual work of interacting with the backend security provider, whether it be a database, LDAP server, or something else. [Image] 15.4.1. Configuring IdentityManager The identityManager component allows for separate identity stores to be configured for authentication and authorization operations. This means that it is possible for users to be authenticated against one identity store, for example an LDAP directory, yet have their roles loaded from another identity store, such as a relational database. Seam provides two IdentityStore implementations out of the box; JpaIdentityStore uses a relational database to store user and role information, and is the default identity store that is used if nothing is explicitly configured in the identityManager component. The other implementation that is provided is LdapIdentityStore, which uses an LDAP directory to store users and roles. There are two configurable properties for the identityManager component - identityStore and roleIdentityStore. The value for these properties must be an EL expression referring to a Seam component implementing the IdentityStore interface. As already mentioned, if left unconfigured then JpaIdentityStore will be assumed by default. If only the identityStore property is configured, then the same value will be used for roleIdentityStore also. For example, the following entry in components.xml will configure identityManager to use an LdapIdentityStore for both user-related and role-related operations: The following example configures identityManager to use an LdapIdentityStore for user-related operations, and JpaIdentityStore for role-related operations: The following sections explain both of these identity store implementations in greater detail. 15.4.2. JpaIdentityStore This identity store allows for users and roles to be stored inside a relational database. It is designed to be as unrestrictive as possible in regards to database schema design, allowing a great deal of flexibility in the underlying table structure. This is achieved through the use of a set of special annotations, allowing entity beans to be configured to store user and role records. 15.4.2.1. Configuring JpaIdentityStore JpaIdentityStore requires that both the user-class and role-class properties are configured. These properties should refer to the entity classes that are to be used to store both user and role records, respectively. The following example shows the configuration from components.xml in the SeamSpace example: 15.4.2.2. Configuring the Entities As already mentioned, a set of special annotations are used to configure entity beans for storing users and roles. The following table lists each of the annotations, and their descriptions. Table 15.1. User Entity Annotations Annotation Status Description @UserPrincipal Required This annotation marks the field or method containing the user's username. @UserPassword Required This annotation marks the field or method containing the user's password. It allows a hash algorithm to be specified for password hashing. Possible values for hash are md5, sha and none. E.g: @UserPassword(hash = "md5") public String getPasswordHash() { return passwordHash; } If an application requires a hash algorithm that isn't supported natively by Seam, it is possible to extend the PasswordHash component to implement other hashing algorithms. @UserFirstName Optional This annotation marks the field or method containing the user's first name. @UserLastName Optional This annotation marks the field or method containing the user's last name. @UserEnabled Optional This annotation marks the field or method containing the enabled status of the user. This should be a boolean property, and if not present then all user accounts are assumed to be enabled. @UserRoles Required This annotation marks the field or method containing the roles of the user. This property will be described in more detail further down. Table 15.2. Role Entity Annotations Annotation Status Description @RoleName Required This annotation marks the field or method containing the name of the role. @RoleGroups Optional This annotation marks the field or method containing the group memberships of the role. @RoleConditional Optional This annotation marks the field or method indicating whether the role is conditional or not. Conditional roles are explained later in this chapter. 15.4.2.3. Entity Bean Examples As mentioned previously, JpaIdentityStore is designed to be as flexible as possible when it comes to the database schema design of your user and role tables. This section looks at a number of possible database schemas that can be used to store user and role records. 15.4.2.3.1. Minimal schema example In this bare minimal example, a simple user and role table are linked via a many-to-many relationship using a cross-reference table named UserRoles. [Image] @Entity public class User { private Integer userId; private String username; private String passwordHash; private Set roles; @Id @GeneratedValue public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @UserPrincipal public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @UserPassword(hash = "md5") public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } @UserRoles @ManyToMany(targetEntity = Role.class) @JoinTable(name = "UserRoles", joinColumns = @JoinColumn(name = "UserId"), inverseJoinColumns = @JoinColumn(name = "RoleId")) public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } } @Entity public class Role { private Integer roleId; private String rolename; @Id @Generated public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @RoleName public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } } 15.4.2.3.2. Complex Schema Example This example builds on the above minimal example by including all of the optional fields, and allowing group memberships for roles. [Image] @Entity public class User { private Integer userId; private String username; private String passwordHash; private Set roles; private String firstname; private String lastname; private boolean enabled; @Id @GeneratedValue public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @UserPrincipal public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @UserPassword(hash = "md5") public String getPasswordHash() { return passwordHash; } public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; } @UserFirstName public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } @UserLastName public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } @UserEnabled public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @UserRoles @ManyToMany(targetEntity = Role.class) @JoinTable(name = "UserRoles", joinColumns = @JoinColumn(name = "UserId"), inverseJoinColumns = @JoinColumn(name = "RoleId")) public Set getRoles() { return roles; } public void setRoles(Set roles) { this.roles = roles; } } @Entity public class Role { private Integer roleId; private String rolename; private boolean conditional; @Id @Generated public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } @RoleName public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } @RoleConditional public boolean isConditional() { return conditional; } public void setConditional(boolean conditional) { this.conditional = conditional; } @RoleGroups @ManyToMany(targetEntity = Role.class) @JoinTable(name = "RoleGroups", joinColumns = @JoinColumn(name = "RoleId"), inverseJoinColumns = @JoinColumn(name = "GroupId")) public Set getGroups() { return groups; } public void setGroups(Set groups) { this.groups = groups; } } 15.4.2.4. JpaIdentityStore Events When using JpaIdentityStore as the identity store implementation with IdentityManager, a few events are raised as a result of invoking certain IdentityManager methods. 15.4.2.4.1. JpaIdentityStore.EVENT_PRE_PERSIST_USER This event is raised in response to calling IdentityManager.createUser(). Just before the user entity is persisted to the database, this event will be raised passing the entity instance as an event parameter. The entity will be an instance of the user-class configured for JpaIdentityStore. Writing an observer for this event may be useful for setting additional field values on the entity, which aren't set as part of the standard createUser() functionality. 15.4.2.4.2. JpaIdentityStore.EVENT_USER_CREATED This event is also raised in response to calling IdentityManager.createUser(). However, it is raised after the user entity has already been persisted to the database. Like the EVENT_PRE_PERSIST_USER event, it also passes the entity instance as an event parameter. It may be useful to observe this event if you also need to persist other entities that reference the user entity, for example contact detail records or other user-specific data. 15.4.2.4.3. JpaIdentityStore.EVENT_USER_AUTHENTICATED This event is raised when calling IdentityManager.authenticate(). It passes the user entity instance as the event parameter, and is useful for reading additional properties from the user entity that is being authenticated. 15.4.3. LdapIdentityStore This identity store implementation is designed for working with user records stored in an LDAP directory. It is very highly configurable, allowing great flexibility in how both users and roles are stored in the directory. The following sections describe the configuration options for this identity store, and provide some configuration examples. 15.4.3.1. Configuring LdapIdentityStore The following table describes the available properties that can be configured in components.xml for LdapIdentityStore. Table 15.3. LdapIdentityStore Configuration Properties Property Default Value Description server-address localhost The address of the LDAP server. server-port 389 The port number that the LDAP server is listening on. user-context-DN ou=Person,dc=acme,dc=com The Distinguished Name (DN) of the context containing user records. user-DN-prefix uid= This value is prefixed to the front of the username to locate the user's record. user-DN-suffix ,ou=Person,dc=acme,dc=com This value is appended to the end of the username to locate the user's record. role-context-DN ou=Role,dc=acme,dc=com The DN of the context containing role records. role-DN-prefix cn= This value is prefixed to the front of the role name to form the DN for locating the role record. role-DN-suffix ,ou=Roles,dc=acme,dc=com This value is appended to the role name to form the DN for locating the role record. bind-DN cn=Manager,dc=acme,dc=com This is the context used to bind to the LDAP server. bind-credentials secret These are the credentials (the password) used to bind to the LDAP server. user-role-attribute roles This is the name of the attribute of the user record that contains the list of roles that the user is a member of. role-attribute-is-DN true This boolean property indicates whether the role attribute of the user record is itself a distinguished name. user-name-attribute uid Indicates which attribute of the user record contains the username. user-password-attribute userPassword Indicates which attribute of the user record contains the user's password. first-name-attribute null Indicates which attribute of the user record contains the user's first name. last-name-attribute sn Indicates which attribute of the user record contains the user's last name. full-name-attribute cn Indicates which attribute of the user record contains the user's full (common) name. enabled-attribute null Indicates which attribute of the user record determines whether the user is enabled. role-name-attribute cn Indicates which attribute of the role record contains the name of the role. object-class-attribute objectClass Indicates which attribute determines the class of an object in the directory. role-object-classes organizationalRole An array of the object classes that new role records should be created as. user-object-classes person,uidObject An array of the object classes that new user records should be created as. 15.4.3.2. LdapIdentityStore Configuration Example The following configuration example shows how LdapIdentityStore may be configured for an LDAP directory running on fictional host directory.mycompany.com. The users are stored within this directory under the context ou=Person,dc=mycompany,dc=com, and are identified using the uid attribute (which corresponds to their username). Roles are stored in their own context, ou=Roles,dc=mycompany,dc=com and referenced from the user's entry via the roles attribute. Role entries are identified by their common name (the cn attribute) , which corresponds to the role name. In this example, users may be disabled by setting the value of their enabled attribute to false. 15.4.4. Writing your own IdentityStore Writing your own identity store implementation allows you to authenticate and perform identity management operations against security providers that aren't supported out of the box by Seam. Only a single class is required to achieve this, and it must implement the org.jboss.seam.security.management.IdentityStore interface. Please refer to the JavaDoc for IdentityStore for a description of the methods that must be implemented. 15.4.5. Authentication with Identity Management If you are using the Identity Management features in your Seam application, then it is not required to provide an authenticator component (see previous Authentication section) to enable authentication. Simply omit the authenticator-method from the identity configuration in components.xml, and the SeamLoginModule will by default use IdentityManager to authenticate your application's users, without any special configuration required. 15.4.6. Using IdentityManager The IdentityManager can be accessed either by injecting it into your Seam component as follows: @In IdentityManager identityManager; or by accessing it through its static instance() method: IdentityManager identityManager = IdentityManager.instance(); The following table describes IdentityManager's API methods: Table 15.4. Identity Management API Method Returns Description createUser(String name, String password) boolean Creates a new user account, with the specified name and password. Returns true if successful, or false if not. deleteUser(String name) boolean Deletes the user account with the specified name. Returns true if successful, or false if not. createRole(String role) boolean Creates a new role, with the specified name. Returns true if successful, or false if not. deleteRole(String name) boolean Deletes the role with the specified name. Returns true if successful, or false if not. enableUser(String name) boolean Enables the user account with the specified name. Accounts that are not enabled are not able to authenticate. Returns true if successful, or false if not. disableUser(String name) boolean Disables the user account with the specified name. Returns true if successful, or false if not. changePassword(String name, String password) boolean Changes the password for the user account with the specified name. Returns true if successful, or false if not. isUserEnabled(String name) boolean Returns true if the specified user account is enabled, or false if it isn't. grantRole(String name, String role) boolean Grants the specified role to the specified user or role. The role must already exist for it to be granted. Returns true if the role is successfully granted, or false if it is already granted to the user. revokeRole(String name, String role) boolean Revokes the specified role from the specified user or role. Returns true if the specified user is a member of the role and it is successfully revoked, or false if the user is not a member of the role. userExists(String name) boolean Returns true if the specified user exists, or false if it doesn't. listUsers() List Returns a list of all user names, sorted in alpha-numeric order. listUsers(String filter) List Returns a list of all user names filtered by the specified filter parameter, sorted in alpha-numeric order. listRoles() List Returns a list of all role names. getGrantedRoles(String name) List Returns a list of the names of all the roles explicitly granted to the specified user name. getImpliedRoles(String name) List Returns a list of the names of all the roles implicitly granted to the specified user name. Implicitly granted roles include those that are not directly granted to a user, rather they are granted to the roles that the user is a member of. For example, is the admin role is a member of the user role, and a user is a member of the admin role, then the implied roles for the user are both the admin, and user roles. authenticate(String name, String password) boolean Authenticates the specified username and password using the configured Identity Store. Returns true if successful or false if authentication failed. Successful authentication implies nothing beyond the return value of the method. It does not change the state of the Identity component - to perform a proper Seam login the Identity.login() must be used instead. addRoleToGroup(String role, String group) boolean Adds the specified role as a member of the specified group. Returns true if the operation is successful. removeRoleFromGroup(String role, String group) boolean Removes the specified role from the specified group. Returns true if the operation is successful. listRoles() List Lists the names of all roles. Using the Identity Management API requires that the calling user has the appropriate authorization to invoke its methods. The following table describes the permission requirements for each of the methods in IdentityManager. The permission targets listed below are literal String values. Table 15.5. Identity Management Security Permissions Method Permission Target Permission Action createUser() seam.user create deleteUser() seam.user delete createRole() seam.role create deleteRole() seam.role delete enableUser() seam.user update disableUser() seam.user update changePassword() seam.user update isUserEnabled() seam.user read grantRole() seam.user update revokeRole() seam.user update userExists() seam.user read listUsers() seam.user read listRoles() seam.role read addRoleToGroup() seam.role update removeRoleFromGroup() seam.role update The following code listing provides an example set of security rules that grants access to all Identity Management-related methods to members of the admin role: rule ManageUsers no-loop activation-group "permissions" when check: PermissionCheck(name == "seam.user", granted == false) Role(name == "admin") then check.grant(); end rule ManageRoles no-loop activation-group "permissions" when check: PermissionCheck(name == "seam.role", granted == false) Role(name == "admin") then check.grant(); end 15.5. Error Messages The security API produces a number of default faces messages for various security-related events. The following table lists the message keys that can be used to override these messages by specifying them in a message.properties resource file. To suppress the message, just put the key with an empty value in the resource file. Table 15.6. Security Message Keys Message Key Description org.jboss.seam.loginSuccessful This message is produced when a user successfully logs in via the security API. org.jboss.seam.loginFailed This message is produced when the login process fails, either because the user provided an incorrect username or password, or because authentication failed in some other way. org.jboss.seam.NotLoggedIn This message is produced when a user attempts to perform an action or access a page that requires a security check, and the user is not currently authenticated. org.jboss.seam.AlreadyLoggedIn This message is produced when a user that is already authenticated attempts to log in again. 15.6. Authorization There are a number of authorization mechanisms provided by the Seam Security API for securing access to components, component methods, and pages. This section describes each of these. An important thing to note is that if you wish to use any of the advanced features (such as rule-based permissions) then your components.xml may need to be configured to support this - see the Configuration section above. 15.6.1. Core concepts Seam Security is built around the premise of users being granted roles and/or permissions, allowing them to perform operations that may not otherwise be permissible for users without the necessary security privileges. Each of the authorization mechanisms provided by the Seam Security API are built upon this core concept of roles and permissions, with an extensible framework providing multiple ways to secure application resources. 15.6.1.1. What is a role? A role is a group, or type, of user that may have been granted certain privileges for performing one or more specific actions within an application. They are simple constructs, consisting of just a name such as "admin", "user", "customer", etc. They can be granted either to users (or in some cases to other roles), and are used to create logical groups of users for the convenient assignment of specific application privileges. [Image] 15.6.1.2. What is a permission? A permission is a privilege (sometimes once-off) for performing a single, specific action. It is entirely possible to build an application using nothing but permissions, however roles offer a higher level of convenience when granting privileges to groups of users. They are slightly more complex in structure than roles, essentially consisting of three "aspects"; a target, an action, and a recipient. The target of a permission is the object (or an arbitrary name or class) for which a particular action is allowed to be performed by a specific recipient (or user). For example, the user "Bob" may have permission to delete customer objects. In this case, the permission target may be "customer", the permission action would be "delete" and the recipient would be "Bob". [Image] Within this documentation, permissions are generally represented in the form target:action (omitting the recipient, although in reality one is always required). 15.6.2. Securing components Let's start by examining the simplest form of authorization, component security, starting with the @Restrict annotation. @Restrict vs Typesafe security annotations While using the @Restrict annotation provides a powerful and flexible method for security component methods due to its ability to support EL expressions, it is recommended that the typesafe equivalent (described later) be used, at least for the compile-time safety it provides. 15.6.2.1. The @Restrict annotation Seam components may be secured either at the method or the class level, using the @Restrict annotation. If both a method and it's declaring class are annotated with @Restrict, the method restriction will take precedence (and the class restriction will not apply). If a method invocation fails a security check, then an exception will be thrown as per the contract for Identity.checkRestriction() (see Inline Restrictions). A @Restrict on just the component class itself is equivalent to adding @Restrict to each of its methods. An empty @Restrict implies a permission check of componentName:methodName. Take for example the following component method: @Name("account") public class AccountAction { @Restrict public void delete() { ... } } 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')}"). Now let's look at another example: @Restrict @Name("account") public class AccountAction { public void insert() { ... } @Restrict("#{s:hasRole('admin')}") public void delete() { ... } } This time, the component class itself is annotated with @Restrict. This means that any methods without an overriding @Restrict annotation require an implicit permission check. In the case of this example, 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 correspondingly named methods of the Identity class. These functions can be used within any EL expression throughout the entirety of the security API. Being an EL expression, the value of the @Restrict annotation may reference any objects that exist within a Seam context. This is extremely useful when performing permission checks for a specific object instance. Look at this example: @Name("account") public class AccountAction { @In Account selectedAccount; @Restrict("#{s:hasPermission(selectedAccount,'modify')}") public void modify() { selectedAccount.modify(); } } The interesting thing to note from this example is the reference to selectedAccount seen within the hasPermission() function call. The value of this variable will be looked up from within the Seam context, and passed to the hasPermission() method in Identity, which in this case can then determine 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 @Restrict annotation. In this situation, simply use Identity.checkRestriction() to evaluate a security expression, like this: public void deleteCustomer() { Identity.instance().checkRestriction("#{s:hasPermission(selectedCustomer,'delete')}"); } 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: if (!Identity.instance().hasRole("admin")) throw new AuthorizationException("Must be admin to perform this action"); if (!Identity.instance().hasPermission("customer", "create")) throw new AuthorizationException("You may not create new customers"); 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 which they 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 same EL 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 login form 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's pretend there is a menu on the page that contains some actions which should only be accessible to users in the manager role. Here's one way that these could be written: Manager Reports This is also quite straight forward. If the user is not a member of the manager role, then the outputLink will not be rendered. The rendered attribute can generally be used on the control itself, or on a surrounding or control. Now for something more complex. Let's say you have a h:dataTable control on a page listing records 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 to determine whether the user has the requested permission for that object or not. Here's how a dataTable with secured links might look: Name #{cl.name} City #{cl.city} Action 15.6.4. Securing pages Page security requires that the application is using a pages.xml file, however is extremely simple to configure. Simply include a 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 (form submission) originates from the page. Otherwise, the specified restriction will be evaluated as a standard security expression. Here's a couple of examples: This page has an implied permission of /settings.xhtml:render required for non-faces requests and an implied permission of /settings.xhtml:restore for faces requests. #{s:hasRole('admin')} 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 Seam security also makes it possible to apply security restrictions to read, insert, update and delete actions for entities. To secure all actions for an entity class, add a @Restrict annotation on the class itself: @Entity @Name("customer") @Restrict public class Customer { ... } If no expression is specified in the @Restrict annotation, the default security check that is performed is a permission check of entity:action, where the permission target is the entity instance, 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 relevent entity lifecycle method (annotated as follows): * @PostLoad - Called after an entity instance is loaded from the database. Use this method to configure a read permission. * @PrePersist - Called before a new instance of the entity is inserted. Use this method to configure an insert permission. * @PreUpdate - Called before an entity is updated. Use this method to configure an update permission. * @PreRemove - Called before an entity is deleted. Use this method to configure a delete permission. Here's an example of how an entity would be configured to perform a security check for any insert operations. Please note that the method is not required to do anything, the only important thing in regard to security is how it is annotated: @PrePersist @Restrict public void prePersist() {} Using /META-INF/orm.xml Вы так же можете определить метод возврата в /META-INF/orm.xml: Конечно, все еще необходимо описать метод prePersist() в Customer с помощью @Restrict And here's an example of an entity permission rule that checks if the authenticated user is allowed to insert a new MemberBlog record (from the seamspace example). The entity for which the security check is being made is automatically inserted into the working memory (in this case MemberBlog): rule InsertMemberBlog no-loop activation-group "permissions" when principal: Principal() memberBlog: MemberBlog(member : member -> (member.getUsername().equals(principal.getName()))) check: PermissionCheck(target == memberBlog, action == "insert", granted == false) then check.grant(); end; This rule will grant the permission memberBlog:insert if the currently authenticated user (indicated by the Principal fact) has the same name as the member for which the blog entry is being created. The "principal: Principal()" structure that can be seen in the example code is a variable binding - it binds the instance of the Principal object from the working memory (placed there during authentication) and assigns it to a variable called principal. Variable bindings allow the value to be referred to in other places, such as the following 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 this listener by using the following META-INF/orm.xml file: 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.6.6. Typesafe Permission Annotations Seam provides a number of annotations that may be used as an alternative to @Restrict, which have the added advantage of providing compile-time safety as they don't support arbitrary EL expressions in the same way that @Restrict does. Out of the box, Seam comes with annotations for standard CRUD-based permissions, however it is a simple matter to add your own. The following annotations are provided in the org.jboss.seam.annotations.security package: * @Insert * @Read * @Update * @Delete To use these annotations, simply place them on the method or parameter for which you wish to perform a security check. If placed on a method, then they should specify a target class for which the permission will be checked. Take the following example: @Insert(Customer.class) public void createCustomer() { ... } In this example, a permission check will be performed for the user to ensure that they have the rights to create new Customer objects. The target of the permission check will be Customer.class (the actual java.lang.Class instance itself), and the action is the lower case representation of the annotation name, which in this example is insert. It is also possible to annotate the parameters of a component method in the same way. If this is done, then it is not required to specify a permission target (as the parameter value itself will be the target of the permission check): public void updateCustomer(@Update Customer customer) { ... } To create your own security annotation, you simply need to annotate it with @PermissionCheck, for example: @Target({METHOD, PARAMETER}) @Documented @Retention(RUNTIME) @Inherited @PermissionCheck public @interface Promote { Class value() default void.class; } If you wish to override the default permisison action name (which is the lower case version of the annotation name) with another value, you can specify it within the @PermissionCheck annotation: @PermissionCheck("upgrade") 15.6.7. Typesafe Role Annotations In addition to supporting typesafe permission annotation, Seam Security also provides typesafe role annotations that allow you to restrict access to component methods based on the role memberships of the currently authenticated user. Seam provides one such annotation out of the box, org.jboss.seam.annotations.security.Admin, used to restrict access to a method to users that are a member of the admin role (so long as your own application supports such a role). To create your own role annotations, simply meta-annotate them with org.jboss.seam.annotations.security.RoleCheck, like in the following example: @Target({METHOD}) @Documented @Retention(RUNTIME) @Inherited @RoleCheck public @interface User { } Any methods subsequently annotated with the @User annotation as shown in the above example will be automatically intercepted and the user checked for the membership of the corresponding role name (which is the lower case version of the annotation name, in this case user). 15.6.8. The Permission Authorization Model Seam Security provides an extensible framework for resolving application permissions. The following class diagram shows an overview of the main components of the permission framework: [Image] The relevant classes are explained in more detail in the following sections. 15.6.8.1. PermissionResolver This is actually an interface, which provides methods for resolving individual object permissions. Seam provides the following built-in PermissionResolver implementations, which are described in more detail later in the chapter: * RuleBasedPermissionResolver - This permission resolver uses Drools to resolve rule-based permission checks. * PersistentPermissionResolver - This permission resolver stores object permissions in a persistent store, such as a relational database. 15.6.8.1.1. Writing your own PermissionResolver It is very simple to implement your own permission resolver. The PermissionResolver interface defines only two methods that must be implemented, as shown by the following table. By deploying your own PermissionResolver implementation in your Seam project, it will be automatically scanned during deployment and registered with the default ResolverChain. Table 15.7. PermissionResolver interface Return type Method Description boolean hasPermission(Object target, String action) This method must resolve whether the currently authenticated user (obtained via a call to Identity.getPrincipal()) has the permission specified by the target and action parameters. It should return true if the user has the permission, or false if they don't. void filterSetByAction(Set targets, String action) This method should remove any objects from the specified set, that would return true if passed to the hasPermission() method with the same action parameter value. 15.6.8.2. ResolverChain A ResolverChain contains an ordered list of PermissionResolvers, for the purpose of resolving object permissions for a particular object class or permission target. The following sequence diagram shows the interaction between the components of the permission framework during a permission check (explanation follows). A permission check can originate from a number of possible sources, for example - the security interceptor, the s:hasPermission EL function, or via an API call to Identity.checkPermission: [Image] * 1. A permission check is initiated somewhere (either in code or via an EL expression) resulting in a call to Identity.hasPermission(). * 1.1. Identity invokes PermissionMapper.resolvePermission(), passing in the permission to be resolved. * 1.1.1. PermissionMapper maintains a Map of ResolverChain instances, keyed by class. It uses this map to locate the correct ResolverChain for the permission's target object. Once it has the correct ResolverChain, it retrieves the list of PermissionResolvers it contains via a call to ResolverChain.getResolvers(). * 1.1.2. For each PermissionResolver in the ResolverChain, the PermissionMapper invokes its hasPermission() method, passing in the permission instance to be checked. If any of the PermissionResolvers return true, then the permission check has succeeded and the PermissionMapper also returns true to Identity. If none of the PermissionResolvers return true, then the permission check has failed. 15.6.9. RuleBasedPermissionResolver One of the built-in permission resolvers provided by Seam, RuleBasedPermissionResolver allows permissions to be evaluated based on a set of Drools (JBoss Rules) security rules. A couple of the advantages of using a rule engine are 1) a centralized location for the business logic that is used to evaluate user permissions, and 2) speed - Drools uses very efficient algorithms for evaluating large numbers of complex rules involving multiple conditions. 15.6.9.1. Requirements If using the rule-based permission features provided by Seam Security, the following jar files are required by Drools to be distributed with your project: * drools-compiler.jar * drools-core.jar * janino.jar * antlr-runtime.jar * mvel14.jar 15.6.9.2. Configuration The configuration for RuleBasedPermissionResolver requires that a Drools rule base is first configured in components.xml. By default, it expects that the rule base is named securityRules, as per the following example: /META-INF/security.drl The default rule base name can be overridden by specifying the security-rules property for RuleBasedPermissionResolver: Once the RuleBase component is configured, it's time to write the security rules. 15.6.9.3. Writing Security Rules The first step to writing security rules is to create a new rule file in the /META-INF directory of your application's jar file. Usually this file would be named something like security.drl, however you can name it whatever you like as long as it is configured correspondingly in components.xml. So what should the security rules file contain? At this stage it might be a good idea to at least skim through the Drools documentation, however to get started here's an extremely simple example: package MyApplicationPermissions; import org.jboss.seam.security.permission.PermissionCheck; import org.jboss.seam.security.Role; rule CanUserDeleteCustomers when c: PermissionCheck(target == "customer", action == "delete") Role(name == "admin") then c.grant(); end Let's break this down step by step. The first thing we see is the package declaration. A package in Drools is essentially a collection of rules. The package name can be anything you want - it doesn't relate to anything else outside the scope of the rule base. The next thing we can notice is a couple of import statements for the PermissionCheck and Role classes. 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 CanUserDeleteCustomers and 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 is known as a left hand side (LHS) and a right hand side (RHS). The LHS consists of the conditional part of the rule, i.e. a list of conditions which must be satisfied for the rule to fire. The LHS is represented by the when section. The RHS is the consequence, or action section of the rule that will only 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. If we look at the LHS of the rule, we see two conditions listed there. Let's examine the first condition: c: PermissionCheck(target == "customer", action == "delete") In plain english, this condition is stating that there must exist a PermissionCheck object with a target property 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 working memory is a session-scoped object that contains the contextual information that is required by the rules engine to make a decision about a permission check. Each time the hasPermission() method is 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 you call hasPermission("account", "create") then a PermissionCheck object with a target equal to "account" and action equal to "create" will be inserted into the working memory for the duration of the permission check. Besides the PermissionCheck facts, there is also a org.jboss.seam.security.Role fact for each of the roles that the authenticated user is a member of. These Role facts are synchronized with the user's authenticated roles at the beginning of every permission check. As a consequence, any Role object that is inserted into the working memory during the course of a permission check will be removed before the next permission check occurs, if the authenticated user is not actually a member of that role. Besides the PermissionCheck and Role facts, the working memory also contains the java.security.Principal object that was created as a result of the authentication process. It is also possible to insert additional long-lived facts into the working memory by calling RuleBasedPermissionResolver.instance().getSecurityContext().insert(), passing the object as a parameter. The exception to this is Role objects, which as already discussed are synchronized at the start 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 (in this case, the PermissionCheck). Moving on to the second line of our LHS, we see this: Role(name == "admin") This condition simply states that there must be a Role object with a name of "admin" within the working memory. As already mentioned, user roles are inserted into the working memory at the beginning of each permission check. So, putting both conditions together, this rule is essentially saying "I will fire if you 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's take a look at the RHS of the rule: c.grant() The RHS consists of Java code, and in this case is invoking the grant() method of the c object, which as 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 is initially 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 action the permission check was intended for. 15.6.9.4. Non-String permission targets So far we have only seen permission checks for String-literal permission targets. It is of course also possible to write security rules for permission targets of more complex types. For example, let's say that you wish to write a security rule to allow your users to create blog comments. The following rule demonstrates how this may be expressed, by requiring the target of the permission check to be an instance of MemberBlog, and also requiring that the currently authenticated user is a member of the user role: rule CanCreateBlogComment no-loop activation-group "permissions" when blog: MemberBlog() check: PermissionCheck(target == blog, action == "create", granted == false) Role(name == "user") then check.grant(); end 15.6.9.5. Wildcard permission checks It is possible to implement a wildcard permission check (which allows all actions for a given permission target), by omitting the action constraint for the PermissionCheck in your rule, like this: rule CanDoAnythingToCustomersIfYouAreAnAdmin when c: PermissionCheck(target == "customer") Role(name == "admin") then c.grant(); end; This rule allows users with the admin role to perform any action for any customer permission check. 15.6.10. PersistentPermissionResolver Another built-in permission resolver provided by Seam, PersistentPermissionResolver allows permissions to be loaded from persistent storage, such as a relational database. This permission resolver provides ACL style instance-based security, allowing for specific object permissions to be assigned to individual users and roles. It also allows for persistent, arbitrarily-named permission targets (not necessarily object/class based) to be assigned in the same way. 15.6.10.1. Configuration Before it can be used, PersistentPermissionResolver must be configured with a valid PermissionStore in components.xml. If not configured, it will attempt to use the default permission store, JpaIdentityStore (see section further down for details). To use a permission store other than the default, configure the permission-store property as follows: 15.6.10.2. Permission Stores A permission store is required for PersistentPermissionResolver to connect to the backend storage where permissions are persisted. Seam provides one PermissionStore implementation out of the box, JpaPermissionStore, which is used to store permissions inside a relational database. It is possible to write your own permission store by implementing the PermissionStore interface, which defines the following methods: Table 15.8. PermissionStore interface Return type Method Description List listPermissions(Object target) This method should return a List of Permission objects representing all the permissions granted for the specified target object. List listPermissions(Object target, String action) This method should return a List of Permission objects representing all the permissions with the specified action, granted for the specified target object. List listPermissions(Set targets, String action) This method should return a List of Permission objects representing all the permissions with the specified action, granted for the specified set of target objects. boolean grantPermission(Permission) This method should persist the specified Permission object to the backend storage, returning true if successful. boolean grantPermissions(List permissions) This method should persist all of the Permission objects contained in the specified List, returning true if successful. boolean revokePermission(Permission permission) This method should remove the specified Permission object from persistent storage. boolean revokePermissions(List permissions) This method should remove all of the Permission objects in the specified list from persistent storage. List listAvailableActions(Object target) This method should return a list of all the available actions (as Strings) for the class of the specified target object. It is used in conjunction with permission management to build the user interface for granting specific class permissions (see section further down). 15.6.10.3. JpaPermissionStore This is the default PermissionStore implementation (and the only one provided by Seam), which uses a relational database to store permissions. Before it can be used it must be configured with either one or two entity classes for storing user and role permissions. These entity classes must be annotated with a special set of security annotations to configure which properties of the entity correspond to various aspects of the permissions being stored. If you wish to use the same entity (i.e. a single database table) to store both user and role permissions, then only the user-permission-class property is required to be configured. If you wish to use separate tables for storing user and role permissions, then in addition to the user-permission-class property you must also configure the role-permission-class property. For example, to configure a single entity class to store both user and role permissions: To configure separate entity classes for storing user and role permissions: 15.6.10.3.1. Permission annotations As mentioned, the entity classes that contain the user and role permissions must be configured with a special set of annotations, contained within the org.jboss.seam.annotations.security.permission package. The following table lists each of these annotations along with a description of how they are used: Table 15.9. Entity Permission annotations Annotation Target Description @PermissionTarget FIELD,METHOD This annotation identifies the property of the entity that will contain the permission target. The property should be of type java.lang.String. @PermissionAction FIELD,METHOD This annotation identifies the property of the entity that will contain the permission action. The property should be of type java.lang.String. @PermissionUser FIELD,METHOD This annotation identifies the property of the entity that will contain the recipient user for the permission. It should be of type java.lang.String and contain the user's username. @PermissionRole FIELD,METHOD This annotation identifies the property of the entity that will contain the recipient role for the permission. It should be of type java.lang.String and contain the role name. @PermissionDiscriminator FIELD,METHOD This annotation should be used when the same entity/table is used to store both user and role permissions. It identifies the property of the entity that is used to discriminate between user and role permissions. By default, if the column value contains the string literal user, then the record will be treated as a user permission. If it contains the string literal role, then it will be treated as a role permission. It is also possible to override these defaults by specifying the userValue and roleValue properties within the annotation. For example, to use u and r instead of user and role, the annotation would be written like this: @PermissionDiscriminator(userValue = "u", roleValue = "r") 15.6.10.3.2. Example Entity Here is an example of an entity class that is used to store both user and role permissions. The following class can be found inside the SeamSpace example: @Entity public class AccountPermission implements Serializable { private Integer permissionId; private String recipient; private String target; private String action; private String discriminator; @Id @GeneratedValue public Integer getPermissionId() { return permissionId; } public void setPermissionId(Integer permissionId) { this.permissionId = permissionId; } @PermissionUser @PermissionRole public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient; } @PermissionTarget public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } @PermissionAction public String getAction() { return action; } public void setAction(String action) { this.action = action; } @PermissionDiscriminator public String getDiscriminator() { return discriminator; } public void setDiscriminator(String discriminator) { this.discriminator = discriminator; } } As can be seen in the above example, the getDiscriminator() method has been annotated with the @PermissionDiscriminator annotation, to allow JpaPermissionStore to determine which records represent user permissions and which represent role permissions. In addition, it can also be seen that the getRecipient() method is annotated with both @PermissionUser and @PermissionRole annotations. This is perfectly valid, and simply means that the recipient property of the entity will either contain the name of the user or the name of the role, depending on the value of the discriminator property. 15.6.10.3.3. Class-specific Permission Configuration A further set of class-specific annotations can be used to configure a specific set of allowable permissions for a target class. These permissions can be found in the org.jboss.seam.annotation.security.permission package: Table 15.10. Class Permission Annotations Annotation Target Description @Permissions TYPE A container annotation, this annotation may contain an array of @Permission annotations. @Permission TYPE This annotation defines a single allowable permission action for the target class. Its action property must be specified, and an optional mask property may also be specified if permission actions are to be persisted as bitmasked values (see next section). Here's an example of the above annotations in action. The following class can also be found in the SeamSpace example: @Permissions({ @Permission(action = "view"), @Permission(action = "comment") }) @Entity public class MemberImage implements Serializable { This example demonstrates how two allowable permission actions, view and comment can be declared for the entity class MemberImage. 15.6.10.3.4. Permission masks By default, multiple permissions for the same target object and recipient will be persisted as a single database record, with the action property/column containing a comma-separated list of the granted actions. To reduce the amount of physical storage required to persist a large number of permissions, it is possible to use a bitmasked integer value (instead of a comma-separated list) to store the list of permission actions. For example, if recipient "Bob" is granted both the view and comment permissions for a particular MemberImage (an entity bean) instance, then by default the action property of the permission entity will contain "view,comment", representing the two granted permission actions. Alternatively, if using bitmasked values for the permission actions, as defined like so: @Permissions({ @Permission(action = "view", mask = 1), @Permission(action = "comment", mask = 2) }) @Entity public class MemberImage implements Serializable { The action property will instead simply contain "3" (with both the 1 bit and 2 bit switched on). Obviously for a large number of allowable actions for any particular target class, the storage required for the permission records is greatly reduced by using bitmasked actions. Obviously, it is very important that the mask values specified are powers of 2. 15.6.10.3.5. Identifier Policy When storing or looking up permissions, JpaPermissionStore must be able to uniquely identify specific object instances to effectively operate on its permissions. To achieve this, an identifier strategy may be assigned to each target class for the generation of unique identifier values. Each identifier strategy implementation knows how to generate unique identifiers for a particular type of class, and it is a simple matter to create new identifier strategies. The IdentifierStrategy interface is very simple, declaring only two methods: public interface IdentifierStrategy { boolean canIdentify(Class targetClass); String getIdentifier(Object target); } The first method, canIdentify() simply returns true if the identifier strategy is capable of generating a unique identifier for the specified target class. The second method, getIdentifier() returns the unique identifier value for the specified target object. Seam provides two IdentifierStrategy implementations, ClassIdentifierStrategy and EntityIdentifierStrategy (see next sections for details). To explicitly configure a specific identifier strategy to use for a particular class, it should be annotated with org.jboss.seam.annotations.security.permission.Identifier, and the value should be set to a concrete implementation of the IdentifierStrategy interface. An optional name property can also be specified, the effect of which is dependent upon the actual IdentifierStrategy implementation used. 15.6.10.3.6. ClassIdentifierStrategy This identifier strategy is used to generate unique identifiers for classes, and will use the value of the name (if specified) in the @Identifier annotation. If there is no name property provided, then it will attempt to use the component name of the class (if the class is a Seam component), or as a last resort it will create an identifier based on the name of the class (excluding the package name). For example, the identifier for the following class will be "customer": @Identifier(name = "customer") public class Customer { The identifier for the following class will be "customerAction": @Name("customerAction") public class CustomerAction { Finally, the identifier for the following class will be "Customer": public class Customer { 15.6.10.3.7. EntityIdentifierStrategy This identifier strategy is used to generate unique identifiers for entity beans. It does so by concatenating the entity name (or otherwise configured name) with a string representation of the primary key value of the entity. The rules for generating the name section of the identifier are similar to ClassIdentifierStrategy. The primary key value (i.e. the id of the entity) is obtained using the PersistenceProvider component, which is able to correctly determine the value regardless of which persistence implementation is used within the Seam application. For entities not annotated with @Entity, it is necessary to explicitly configure the identifier strategy on the entity class itself, for example: @Identifier(value = EntityIdentifierStrategy.class) public class Customer { For an example of the type of identifier values generated, assume we have the following entity class: @Entity public class Customer { private Integer id; private String firstName; private String lastName; @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } For a Customer instance with an id value of 1, the value of the identifier would be "Customer:1". If the entity class is annotated with an explicit identifier name, like so: @Entity @Identifier(name = "cust") public class Customer { Then a Customer with an id value of 123 would have an identifier value of "cust:123". 15.7. Permission Management In much the same way that Seam Security provides an Identity Management API for the management of users and roles, it also provides a Permissions Management API for the management of persistent user permissions, via the PermissionManager component. 15.7.1. PermissionManager The PermissionManager component is an application-scoped Seam component that provides a number of methods for managing permissions. Before it can be used, it must be configured with a permission store (although by default it will attempt to use JpaPermissionStore if it is available). To explicitly configure a custom permission store, specify the permission-store property in components.xml: The following table describes each of the available methods provided by PermissionManager: Table 15.11. PermissionManager API methods Return type Method Description List listPermissions(Object target, String action) Returns a list of Permission objects representing all of the permissions that have been granted for the specified target and action. List listPermissions(Object target) Returns a list of Permission objects representing all of the permissions that have been granted for the specified target and action. boolean grantPermission(Permission permission) Persists (grants) the specified Permission to the backend permission store. Returns true if the operation was successful. boolean grantPermissions(List permissions) Persists (grants) the specified list of Permissions to the backend permission store. Returns true if the operation was successful. boolean revokePermission(Permission permission) Removes (revokes) the specified Permission from the backend permission store. Returns true if the operation was successful. boolean revokePermissions(List permissions) Removes (revokes) the specified list of Permissions from the backend permission store. Returns true if the operation was successful. List listAvailableActions(Object target) Returns a list of the available actions for the specified target object. The actions that this method returns are dependent on the @Permission annotations configured on the target object's class. 15.7.2. Permission checks for PermissionManager operations Invoking the methods of PermissionManager requires that the currently-authenticated user has the appropriate authorization to perform that management operation. The following table lists the required permissions that the current user must have. Table 15.12. Permission Management Security Permissions Method Permission Target Permission Action listPermissions() The specified target seam.read-permissions grantPermission() The target of the specified Permission, or each of the targets for the specified list of Permissions (depending on which method is called). seam.grant-permission grantPermission() The target of the specified Permission. seam.grant-permission grantPermissions() Each of the targets of the specified list of Permissions. seam.grant-permission revokePermission() The target of the specified Permission. seam.revoke-permission revokePermissions() Each of the targets of the specified list of Permissions. seam.revoke-permission 15.8. SSL Security Seam includes basic support for serving sensitive pages via the HTTPS protocol. This is easily configured by specifying a scheme for the page in pages.xml. The following example shows how the view /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 previous example, the following link will use the HTTPS protocol because /login.xhtml is configured to use it: Browsing directly to a view when using the incorrect protocol will cause a redirect to the same view using the correct protocol. For example, browsing to a page that has scheme="https" using HTTP will cause 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 for a only few pages. If no default scheme is specified then the normal behavior is to continue use the current scheme. So once the user accessed a page that required HTTPS, then HTTPS would continue to be used after the user navigated away to other non-HTTPS pages. (While this is good for security, it is not 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 default scheme. You may configure Seam to automatically invalidate the current HTTP session each time the scheme changes. Just add this line to components.xml: This option helps make your system less vulnerable to sniffing of the session id or leakage of sensitive data from pages using HTTPS to other pages using HTTP. 15.8.1. Overriding the default ports If you wish to configure the HTTP and HTTPS ports manually, they may be configured in pages.xml by specifying the http-port and https-port attributes on the pages element: 15.9. CAPTCHA Though strictly not part of the security API, Seam provides a built-in CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) algorithm to prevent automated processes 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 the Captcha challenge images to your pages. This requires the following entry in web.xml: Seam Resource Servlet org.jboss.seam.servlet.SeamResourceServlet Seam Resource Servlet /seam/resource/* 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 the CAPTCHA when the form is submitted. 15.9.3. Customising the CAPTCHA algorithm You may customize the CAPTCHA algorithm by overriding the built-in component: @Name("org.jboss.seam.captcha.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() { BufferedImage img = super.renderChallenge(); img.getGraphics().drawOval(5, 3, 60, 14); //add an obscuring decoration return img; } } 15.10. Security Events The following table describes a number of events (see Chapter 6, Events, interceptors and exception handling) raised by Seam Security in response to certain security-related events. Table 15.13. 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 authenticated attempts to log in again. org.jboss.seam.security.notLoggedIn Raised when a security check fails when the user is not logged in. org.jboss.seam.security.notAuthorized Raised when a security check fails when the user is logged 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 been changed. org.jboss.seam.security.rememberMe Raised when the Identity's rememberMe property is changed. 15.11. Run As Sometimes it may be necessary to perform certain operations with elevated privileges, such as creating a new user account as an unauthenticated user. Seam Security supports such a mechanism via the RunAsOperation class. This class allows either the Principal or Subject, or the user's roles to be overridden for a single set of operations. The following code example demonstrates how RunAsOperation is used, by calling its addRole() method to provide 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. new RunAsOperation() { public void execute() { executePrivilegedOperation(); } }.addRole("admin") .run(); In a similar way, the getPrincipal() or getSubject() methods can also be overriden to specify the 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 special security requirements. The following example (contrived, as credentials would normally be handled by the Credentials component instead) shows an extended Identity component with an additional companyCode field. The install precendence of APPLICATION ensures that this extended Identity gets installed in preference to the built-in Identity. @Name("org.jboss.seam.security.identity") @Scope(SESSION) @Install(precedence = APPLICATION) @BypassInterceptors @Startup public 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() { log.info("###### CUSTOM LOGIN CALLED ######"); return super.login(); } } Warning Note that an Identity component must be marked @Startup, so that it is available immediately after the SESSION context begins. Failing to do this may render certain Seam functionality inoperable in your application. 15.13. OpenID OpenID is a community standard for external web-based authentication. The basic idea is that any web application can supplement (or replace) its local handling of authentication by delegating responsibility to an external OpenID server of the user's chosing. This benefits the user, who no longer has to remember a name and password for every web application he uses, and the developer, who is relieved of some of the burden of maintaining a complex authentication system. When using OpenID, the user selects an OpenID provider, and the provider assigns the user an OpenID. The id will take the form of a URL, for example http://maximoburrito.myopenid.com however, it's acceptable to leave off the http:// part of the identifier when logging into a site. The web application (known as a relying party in OpenID-speak) determines which OpenID server to contact and redirects the user to the remote site for authentication. Upon successful authentication the user is given the (cryptographically secure) token proving his identity and is redirected back to the original web application.The local web application can then be sure the user accessing the application controls the OpenID he presented. It's important to realize at this point that authentication does not imply authorization. The web application still needs to make a determination of how to use that information. The web application could treat the user as instantly logged in and give full access to the system or it could try and map the presented OpenID to a local user account, prompting the user to register if he hasn't already. The choice of how to handle the OpenID is left as a design decision for the local application. 15.13.1. Configuring OpenID Seam uses the openid4java package and requires four additional JARs to make use of the Seam integration. These are: htmlparser.jar, openid4java.jar, openxri-client.jar and openxri-syntax.jar. OpenID processing requires the use of the OpenIdPhaseListener, which should be added to your faces-config.xml file. The phase listener processes the callback from the OpenID provider, allowing re-entry into the local application. org.jboss.seam.security.openid.OpenIdPhaseListener With this configuration, OpenID support is available to your application. The OpenID support component, org.jboss.seam.security.openid.openid, is installed automatically if the openid4java classes are on the classpath. 15.13.2. Presenting an OpenIdDLogin form To initiate an OpenID login, you can present a simply form to the user asking for the user's OpenID. The #{openid.id} value accepts the user's OpenID and the #{openid.login} action initiates an authentication request. When the user submits the login form, he will be redirected to his OpenID provider. The user will eventually return to your application through the Seam pseudo-view /openid.xhtml, which is provided by the OpenIdPhaseListener. Your application can handle the OpenID response by means of a pages.xml navigation from that view, just as if the user had never left your application. 15.13.3. Logging in immediately The simplest strategy is to simply login the user immediately. The following navigation rule shows how to handle this using the #{openid.loginImmediately()} action. OpenID login successful... OpenID login rejected... Thie loginImmediately() action checks to see if the OpenID is valid. If it is valid, it adds an OpenIDPrincipal to the identity component, marks the user as logged in (i.e. #{identity.loggedIn} will be true) and returns true. If the OpenID was not validated, the method returns false, and the user re-enters the application un-authenticated. If the user's OpenID is valid, it will be accessible using the expression #{openid.validatedId} and #{openid.valid} will be true. 15.13.4. Deferring login You may not want the user to be immediately logged in to your application. In that case, your navigation should check the #{openid.valid} property and redirect the user to a local registration or processing page. Actions you might take would be asking for more information and creating a local user account or presenting a captcha to avoid programmatic registrations. When you are done processing, if you want to log the user in, you can call the loginImmediately method, either through EL as shown previously or by directly interaction with the org.jboss.seam.security.openid.OpenId component. Of course, nothing prevents you from writing custom code to interact with the Seam identity component on your own for even more customized behaviour. 15.13.5. Logging out Logging out (forgetting an OpenID association) is done by calling #{openid.logout}. If you are not using Seam security, you can call this method directly. If you are using Seam security, you should continue to use #{identity.logout} and install an event handler to capture the logout event, calling the OpenID logout method. It's important that you do not leave this out or the user will not be able to login again in the same session. Chapter 16. Internationalization, localization and themes 16.1. Internationalizing your app 16.1.1. Application server configuration 16.1.2. Translated application strings 16.1.3. Other encoding settings 16.2. Locales 16.3. Labels 16.3.1. Defining labels 16.3.2. Displaying labels 16.3.3. Faces messages 16.4. Timezones 16.5. Themes 16.6. Persisting locale and theme preferences via cookies Seam makes it easy to build internationalized applications. First, let's walk through all the stages needed to internationalize and localize your app. Then we'll take a look at the components Seam bundles. 16.1. Internationalizing your app A JEE application consists of many components and all of them must be configured properly for your application to be localized. Starting at the bottom, the first step is to ensure that your database server and client is using the correct character encoding for your locale. Normally you'll want to use UTF-8. How to do this is outside 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 from client 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 AS 4.2 change ${JBOSS_HOME}/server/(default)/deploy/jboss-web.deployer/server.xml: There is alternative which is probably better. You can tell JBoss AS that the encoding for the request parameters will be taken from the request: 16.1.2. Translated application strings You'll also need localized strings for all the messages in your application (for example field labels on your views). First you need to ensure that your resource bundle is encoded using the desired character encoding. By default ASCII is used. Although ASCII is enough for many languages, it doesn't provide characters for all languages. Resource bundles must be created in ASCII, or use Unicode escape codes to represent Unicode characters. Since you don't compile a property file to byte code, there is no way to tell the JVM which character set to use. So you must use either ASCII characters or escape characters not in the ASCII character set. You can represent a Unicode character in any Java file using \uXXXX, where XXXX is the hexidecimal representation of the character. You can write your translation of labels (Labels) to your messages resource bundle in the native encoding and then convert the content of the file into the escaped format through the tool native2ascii provided in the JDK. This tool will convert a file written in your native encoding to one that represents non-ASCII characters 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 from UTF-8: $ native2ascii -encoding UTF-8 messages_cs.properties > messages_cs_escaped.properties 16.1.3. Other encoding settings We need to make sure that the view displays your localized data and messages using the correct character set and also any data submitted uses the correct encoding. To set the display character encoding, you need to use the tag (here we tell JSF to use the Czech locale). You may want to change the encoding of the xml document itself if you want to embed localized strings in the xml. To do this alter the encoding attribute in xml declaration as required. Also JSF/Facelets should submit any requests using the specified character encoding, but to make sure any requests that don't specify an encoding you can force the request encoding using a servlet filter. Configure this in components.xml: 16.2. Locales Each user login session has an associated instance of java.util.Locale (available to the application as a component named locale). Under normal circumstances, you won't need to do any special 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 in the list of supported locales from faces-config.xml, use that locale for the rest of the session. * Otherwise, if a default locale was specified in the faces-config.xml, use that locale for the rest 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 good reason 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. All you 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: When the user selects an item from the drop-down, then clicks the command button, the Seam and JSF locales will be overridden for the rest of the session. The brings us to the question of where the supported locales are defined. Typically, you provide a list of locales for which you have matching resource bundles in the element of the JSF configuration file (/META-INF/faces-config.xml). However, you have learned to appreciate that Seam's component configuration mechanism is more powerful than what is provided in Java EE. For that reason, you can configure the supported locales, and the default locale of the server, using the built-in component named org.jboss.seam.international.localeConfig. To use it, you first declare an XML namespace for Seam's international package in the Seam component descriptor. You then define the default locale and supported locales as follows: Naturally, if you pronounce that you support a locale, you better provide a resource bundle to match it! Up next, you'll learn how to define the language-specific labels. 16.3. Labels JSF supports internationalization of user interface labels and descriptive text via the use of . You can use this approach in Seam applications. Alternatively, you can take advantage of the Seam messages component to display templated labels with embedded EL expressions. 16.3.1. Defining labels Seam provides a java.util.ResourceBundle (available to the application as a org.jboss.seam.core.resourceBundle). You'll need to make your internationalized labels available via this special resource bundle. By default, the resource bundle used by Seam is named messages and so you'll 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: Hello=Hello And in messages_en_AU.properties: Hello=G'day You can select a different name for the resource bundle by setting the Seam configuration property named org.jboss.seam.core.resourceLoader.bundleNames. You can even specify a list of resource bundle names to be searched (depth first) for messages. mycompany_messages standard_messages If you want to define a message just for a particular page, you can specify it in a resource bundle with the same name as the JSF view id, with the leading / and trailing file extension removed. So we could put 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: 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'll be able to use them without having to type on every page. Instead, you can simply type: or: Even better, the messages themselves may contain EL expressions: Hello=Hello, #{user.firstName} #{user.lastName} Hello=G'day, #{user.firstName} You can even use the messages in your code: @In private Map messages; @In("#{messages['Hello']}") private String helloMessage; 16.3.3. Faces messages The facesMessages component is a super-convenient way to display success or failure messages to the user. The functionality we just described also works for faces messages: @Name("hello") @Stateless public class HelloBean implements Hello { @In FacesMessages facesMessages; public String sayIt() { facesMessages.addFromResourceBundle("Hello"); } } 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 timezone named org.jboss.seam.international.timezoneSelector. By default, the timezone is the default timezone of the server. Unfortunately, the JSF specification says that all dates and times should be assumed to be UTC, and displayed as UTC, unless a timezone is explicitly specified using . This is an extremely inconvenient default behavior. Seam overrides this behavior, and defaults all dates and times to the Seam timezone. In addition, Seam provides the 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 and themes. First, configure the set of supported themes: default accessible printable Note that 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 default theme is defined as a set of entries in default.properties. For example, default.properties might define: css ../screen.css template /template.xhtml Usually the entries in a theme resource bundle will be paths to CSS styles or images and names of facelets 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 a facelets page: Or, when the page definition resides in a subdirectory: Most powerfully, facelets lets us theme the template used by a : 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 theme preference to a cookie. Simply set the cookie-enabled property in components.xml: default accessible printable Chapter 17. Seam Text 17.1. Basic fomatting 17.2. Entering code and text with special characters 17.3. Links 17.4. Entering HTML Collaboration-oriented websites require a human-friendly markup language for easy entry of formatted text in forum posts, wiki pages, blogs, comments, etc. Seam provides the control for display of formatted text that conforms to the Seam Text language. Seam Text is implemented using an ANTLR-based parser. You don't need to know anything about ANTLR to use it, however. 17.1. Basic fomatting Here is a simple example: It's easy to make *emphasis*, |monospace|, ~deleted text~, super^scripts^ or _underlines_. If we display this using , we will get the following HTML produced:

It's easy to make emphasis, monospace deleted text, superscripts or underlines.

We can use a blank line to indicate a new paragraph, and + to indicate a heading: +This is a big heading You /must/ have some text following a heading! ++This is a smaller heading This 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. (Note that a simple newline is ignored, you need an additional blank line to wrap text into a new paragraph.) This is the HTML that results:

This is a big heading

You must have some text following a heading!

This is a smaller heading

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

Ordered lists are created using the # character. Unordered lists use the = character: An ordered list: #first item #second item #and even the /third/ item An unordered list: =an item =another item

An ordered list:

  1. first item
  2. second item
  3. and even the third item

An unordered list:

  • an item
  • another item
Quoted sections should be surrounded in double quotes: The other guy said: "Nyeah nyeah-nee /nyeah/ nyeah!" But what do you think he means by "nyeah-nee"?

The other guy said:

Nyeah nyeah-nee nyeah nyeah!

But what do you think he means by nyeah-nee?

17.2. Entering code and text with special characters Special characters such as *, | and #, along with HTML characters such as <, > and & may be escaped using \: You can write down equations like 2\*3\=6 and HTML tags like \ using the escape character: \\.

You can write down equations like 2*3=6 and HTML tags like <body> using the escape character: \.

And we can quote code blocks using backticks: My code doesn't work: `for (int i=0; i<100; i--) { doSomething(); }` Any ideas?

My code doesn't work:

for (int i=0; i<100; i--)

{

    doSomething();

}

Any ideas?

Note that inline monospace formatting always escapes (most monospace formatted text is in fact code or tags with many special characters). So you can, for example, write: This is a || example. without escaping any of the characters inside the monospace bars. The downside is that you can't format inline monospace text in any other way (italics, underscore, and so on). 17.3. Links A link may be created using the following syntax: Go to the Seam website at [=>http://jboss.com/products/seam]. Or, if you want to specify the text of the link: Go to [the Seam website=>http://jboss.com/products/seam]. For advanced users, it is even possible to customize the Seam Text parser to understand wikiword links written using this syntax. 17.4. Entering HTML Text may even include a certain limited subset of HTML (don't worry, the subset is chosen to be safe from cross-site scripting attacks). This is useful for creating links: You might want to link to something cool, or even include an image: And for creating tables:
First name:Gavin
Last name:King
But you can do much more if you want! Chapter 18. iText PDF generation 18.1. Using PDF Support 18.1.1. Creating a document 18.1.2. Basic Text Elements 18.1.3. Headers and Footers 18.1.4. Chapters and Sections 18.1.5. Lists 18.1.6. Tables 18.1.7. Document Constants 18.2. Charting 18.3. Bar codes 18.4. Fill-in-forms 18.5. Rendering Swing/AWT components 18.6. Configuring iText 18.7. Further documentation Seam now includes a component set for generating documents using iText. The primary focus of Seam's iText document support is for the generation of PDF doucuments, but Seam also offers basic support 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, which are used to construct views that can render to PDF, and the DocumentStore component, which serves the 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 further configuration needed to use Seam's iText supportfon. The Seam iText module requires the use of Facelets as the view technology. Future versions of the library 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 demonstrates proper deployment packaging, and it contains a number examples that demonstrate the key PDF generation features current supported. 18.1.1. Creating a document Description Documents are generated by facelet XHTML files using tags in the http://jboss.com/products/seam/pdf namespace. Documents should always have the document tag at the root of the document. The document tag prepares Seam to generate a document into the DocumentStore and renders an HTML redirect to that stored content. Attributes * type — The type of the document to be produced. Valid values are PDF, RTF and HTML modes. Seam defaults to PDF generation, and many of the features only work correctly when generating PDF documents. * pageSize — The size of the page to be generate. The most commonly used values would be LETTER and A4. A full list of supported pages sizes can be found in com.lowagie.text.PageSize class. Alternatively, pageSize can provide the width and height of the page directly. The value "612 792", for example, is equivalent to the LETTER page size. * orientation — The orientation of the page. Valid values are portrait and landscape. In landscape mode, the height and width page size values are reversed. * margins — The left, right, top and bottom margin values. * marginMirroring — Indicates that margin settings should be reversed an alternating pages. * disposition — When generating PDFs in a web browser, this determines the HTTP Content-Disposition of the document. Valid values are inline, which indicates the document should be displayed in the browser window if possible, and attachment, which indicates that the document should be treated as a download. The default value is inline. * fileName — For attachments, this value overrides the downloaded file name. Metadata Attributes * title * subject * keywords * author * creator Usage The document goes here. 18.1.2. Basic Text Elements Useful documents will need to contain more than just text; however, the standard UI components are geared towards HTML generation and are not useful for generating PDF content. Instead, Seam provides a special UI components for generating suitable PDF content. Tags like and are the basic foundations of simple documents. Tags like provide style information to all the content surrounging them. Description Most uses of text should be sectioned into paragraphs so that text fragments can be flowed, formatted and styled in logical groups. Attributes * firstLineIndent * extraParagraphSpace * leading * multipliedLeading * spacingBefore — The blank space to be inserted before the element. * spacingAfter — The blank space to be inserted after the element. * indentationLeft * indentationRight * keepTogether Usage This is a simple document. It isn't very fancy. Description The text tag allows text fragments to be produced from application data using normal JSF converter mechanisms. It is very similar to the outputText tag used when rendering HTML documents. Attributes * value — The value to be displayed. This will typically be a value binding expression. Usage The item costs Description The html tag renders HTML content into the PDF. Attributes * value — The text to be displayed. Usage

This is more complex HTML

  • one
  • two
  • three
Description The font tag defines the default font to be used for all 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 combination of : NORMAL, BOLD, ITALIC, OBLIQUE, UNDERLINE, LINE-THROUGH * encoding — The character set encoding. Usage My Title Description p:newPage inserts a page break. Usage Description p:image inserts an image into the document. Images can be be loaded from the classpath or from the web application context using the value attribute. Resources can also be dynamically generated by application code. The imageData attribute can specify a value binding expression whose value is a java.awt.Image object. Attributes * value — A resource name or a method expression binding to an application-generated image. * rotation — The rotation of the image in degrees. * 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 for the image. * indentationLeft * indentationRight * spacingBefore — The blank space to be inserted before the element. * spacingAfter — The blank space to be inserted after the element. * widthPercentage * initialRotation * dpi * scalePercent — The scaling factor (as a percentage) to use for the image. This can be expressed as a single percentage value or as two percentage values representing separate x and y scaling percentages. * wrap * underlying Usage Description p:anchor defines clickable links from a document. It supports the following attributes: Attributes * name — The name of an in-document anchor destination. * reference — The destination the link refers to. Links to other points in the document should begin with a "#". For example, "#link1" to refer to an anchor postion with a name of link1. Links may also be a full URL to point to a resource outside of the document. Usage Reason 1 ... It's the quickest way to get "rich" ... 18.1.3. Headers and Footers Description The p:header and p:footer components provide the ability to place header and footer text on each page of a generated document. Header and footer declarations should appear at the beginning of a document. Attributes * alignment — The alignment of the header/footer box section. (see Section 18.1.7.2, “Alignment Values” for alignment values) * backgroundColor — The background color of the header/footer box. (see Section 18.1.7.1, “Color Values” for color values) * borderColor — The border color of the header/footer box. Individual border sides can be set using borderColorLeft, borderColorRight, borderColorTop and borderColorBottom.(see Section 18.1.7.1, “Color Values” for color values) * borderWidth — The width of the border. Inidvidual border sides can be specified using borderWidthLeft, borderWidthRight, borderWidthTop and borderWidthBottom. Usage Why Seam? [] Description The current page number can be placed inside of a header or footer using the p:pageNumber tag. The page number tag can only be used in the context of a header or footer and can only be used once. Usage Why Seam? [] 18.1.4. Chapters and Sections Description If the generated document follows a book/article structure, the p:chapter and p:section tags can be used to provide the necessary structure. Sections can only be used inside of chapters, but they may be nested arbitrarily deep. Most PDF viewers provide easy navigation between chapters and sections in a document. Attributes * alignment — The alignment of the header/footer box section. (see Section 18.1.7.2, “Alignment Values” for alignment values) * number — The chapter number. Every chapter should be assigned a chapter number. * numberDepth — The depth of numbering for section. All sections are numbered relative to their surrounding chapter/sections. The fourth section of of the first section of chapter three would be section 3.1.4, if displayed at the default number depth of three. To omit the chapter number, a number depth of 2 should be used. In that case, the section number would be displayed as 1.4. Usage Hello Hello #{user.name}! Goodbye Goodbye #{user.name}. Description Any chapter or section can contain a p:title. The title will be displayed next to the chapter/section number. The body of the title may contain raw text or may be a p:paragraph. 18.1.5. Lists List structures can be displayed using the p:list and p:listItem tags. Lists may contain arbitrarily-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. #{doc.name} Attributes * style — The ordering/bulleting style of list. One of: NUMBERED, LETTERED, GREEK, ROMAN, ZAPFDINGBATS, ZAPFDINGBATS_NUMBER. If no style is given, the list items are bulleted. * listSymbol — For bulleted lists, specifies the bullet symbol. * indent — The indentation level of the list. * lowerCase — For list styles using letters, indicates whether the letters should be lower case. * charNumber — For ZAPFDINGBATS, indicates the character code of the bullet character. * numberType — For ZAPFDINGBATS_NUMBER, indicates the numbering style. Usage #{doc.name} Description p:listItem supports the following attributes: Attributes * alignment — The alignment of the header/footer box section. (see Section 18.1.7.2, “Alignment Values” for alignment values) * alignment — The alignment of the list item. (See Section 18.1.7.2, “Alignment Values” for possible values) * indentationLeft — The left indentation amount. * indentationRight — The right indentation amount. * listSymbol — Overrides the default list symbol 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 a row. Header and footer rows can be declared, and the headers and footers will be repeated in the event a table structure spans multiple pages. 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 each column. There should be one value for each column. For example: widths="2 1 1" would indicate that there are 3 columns and the first column should be twice the size of the second and third column. * headerRows — The initial number of rows which are considered to be headers or footer rows and should be repeated if the table spans multiple pages. * footerRows — The number of rows that are considered to be footer rows. This value is subtracted from the headerRows value. If document has 2 rows which make up the header and one row that makes up the footer, headerRows should be set to 3 and footerRows should be set to 1 * widthPercentage — The percentage of the page width that the table spans. * horizontalAlignment — The horizontal alignment of the table. (See Section 18.1.7.2, “Alignment Values” for possible values) * skipFirstHeader * runDirection * lockedWidth * splitRows * spacingBefore — The blank space to be inserted before the element. * spacingAfter — The blank space to be inserted after the element. * extendLastRow * headersInEvent * splitLate * keepTogether Usage name owner size #{doc.name} #{doc.user.name} #{doc.size} Description p:cell supports the following attributes. Attributes * colspan — Cells can span more than one column by declaring a colspan greater than 1. Tables do not have the ability to span across multiple rows. * horizontalAlignment — The horizontal alignment of the cell. (see Section 18.1.7.2, “Alignment Values” for possible values) * verticalAlignment — The vertical alignment of the cell. (see Section 18.1.7.2, “Alignment Values” for possible values) * padding — Padding on a given side can also 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 Seam documents do not yet support a full color specification. Currently, only named colors are supported. 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.2. Charting Charting support is also provided with jboss-seam-pdf.jar. Charts can be used in PDF documents or 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 of charts are currently supported: pie charts, bar charts and line charts. Description Displays a bar chart. Attributes * borderVisible — Controls whether or not a border is displayed around the entire chart. * borderPaint — The color of the border, if visible; * borderBackgroundPaint — The default background color of the chart. * borderStroke — * domainAxisLabel — The text label for the domain axis. * domainAxisPaint — The color of the domain axis label. * domainGridlinesVisible— Controls whether or not gridlines for the domain axis are shown on the chart. * domainGridlinePaint— The color of the domain gridlines, if visible. * domainGridlineStroke — The stroke style of the domain gridleines, if visible. * height — The height of the chart. * width — The width of the chart. * is3D — A boolean value indicating that the chart should be rendered in 3D instead of 2D. * legend — A boolean value indicating whether or not the chart should include a legend. * legendItemPaint— The default color of the text labels in the legend. * legendItemBackgoundPaint— The background color for the legend, if different from the chart background color. * legendOutlinePaint— The color of the border around the legend. * orientation — The orientation of the plot, either vertical (the default) or horizontal. * plotBackgroundPaint— The color of the plot background. * plotBackgroundAlpha— The alpha (transparency) level of the plot background. It should be a number between 0 (completely transparent) and 1 (completely opaque). * plotForegroundAlpha— The alpha (transparency) level of the plot. It should be a number between 0 (completely transparent) and 1 (completely opaque). * plotOutlinePaint— The color of the range gridlines, if visible. * plotOutlineStroke — The stroke style of the range gridleines, if visible. * rangeAxisLabel — The text label for the range axis. * rangeAxisPaint — The color of the range axis label. * rangeGridlinesVisible— Controls whether or not gridlines for the range axis are shown on the chart. * rangeGridlinePaint— The color of the range gridlines, if visible. * rangeGridlineStroke — The stroke style of the range gridleines, if visible. * title — The chart title text. * titlePaint— The color of the chart title text. * titleBackgroundPaint— The background color around the chart title. * width — The width of the chart. Usage Description Displays a line chart. Attributes * borderVisible — Controls whether or not a border is displayed around the entire chart. * borderPaint — The color of the border, if visible; * borderBackgroundPaint — The default background color of the chart. * borderStroke — * domainAxisLabel — The text label for the domain axis. * domainAxisPaint — The color of the domain axis label. * domainGridlinesVisible— Controls whether or not gridlines for the domain axis are shown on the chart. * domainGridlinePaint— The color of the domain gridlines, if visible. * domainGridlineStroke — The stroke style of the domain gridleines, if visible. * height — The height of the chart. * width — The width of the chart. * is3D — A boolean value indicating that the chart should be rendered in 3D instead of 2D. * legend — A boolean value indicating whether or not the chart should include a legend. * legendItemPaint— The default color of the text labels in the legend. * legendItemBackgoundPaint— The background color for the legend, if different from the chart background color. * legendOutlinePaint— The color of the border around the legend. * orientation — The orientation of the plot, either vertical (the default) or horizontal. * plotBackgroundPaint— The color of the plot background. * plotBackgroundAlpha— The alpha (transparency) level of the plot background. It should be a number between 0 (completely transparent) and 1 (completely opaque). * plotForegroundAlpha— The alpha (transparency) level of the plot. It should be a number between 0 (completely transparent) and 1 (completely opaque). * plotOutlinePaint— The color of the range gridlines, if visible. * plotOutlineStroke — The stroke style of the range gridleines, if visible. * rangeAxisLabel — The text label for the range axis. * rangeAxisPaint — The color of the range axis label. * rangeGridlinesVisible— Controls whether or not gridlines for the range axis are shown on the chart. * rangeGridlinePaint— The color of the range gridlines, if visible. * rangeGridlineStroke — The stroke style of the range gridleines, if visible. * title — The chart title text. * titlePaint— The color of the chart title text. * titleBackgroundPaint— The background color around the chart title. * width — The width of the chart. Usage Description Displays a pie chart. Attributes * title— The chart title text. * label— The default label text for pie sections. * legend— A boolean value indicating whether or not the chart should include a legend. Default value is true * is3D—A boolean value indicating that the chart should be rendered in 3D instead of 2D. * labelLinkMargin— The link margin for labels. * labelLinkPaint— The paint used for the label linking lines. * labelLinkStroke— he stroke used for the label linking lines. * labelLinksVisible— A flag that controls whether or not the label links are drawn. * labelOutlinePaint— The paint used to draw the outline of the section labels. * labelOutlineStroke— The stroke used to draw the outline of the section labels. * labelShadowPaint— The paint used to draw the shadow for the section labels. * labelPaint— The color used to draw the section labels * labelGap— The gap between the labels and the plot as a percentage of the plot width. * labelBackgroundPaint— The color used to draw the background of the section labels. If this is null, the background is not filled. * startAngle— The starting angle of the first section. * circular— A boolean value indicating that the chart should be drawn as a circle. If false, the chart is drawn as an ellipse. The default is true. * direction— The direction the pie section are drawn. One of: clockwise or anticlockwise. The default is clockwise. * sectionOutlinePaint— The outline paint for all sections. * sectionOutlineStroke— The outline stroke for all sections * sectionOutlinesVisible— Indicates whether an outline is drawn for each section in the plot. * baseSectionOutlinePaint— The base section outline paint. * baseSectionPaint— The base section paint. * baseSectionOutlineStroke— The base section outline stroke. Usage Description Category data can be broken down into series. The series tag is used to categorize a set of data with a series and apply styling to the entire series. Attributes * key — The series name. * seriesPaint — The color of each item in the series * seriesOutlinePaint — The outline color for each item in the series. * seriesOutlineStroke — The stroke used to draw each item in the series. * seriesVisible — A boolean indicating if the series should be displayed. * seriesVisibleInLegend — A boolean indiciating if the series should be listed in the legend. Usage Description The data tag describes each data point to be displayed in the graph. Attributes * key — The name of the data item. * series — The series name, when not embedded inside a . * value — The numeric data value. * explodedPercent — For pie charts, indicates how exploded a from the pie a piece is. * sectionOutlinePaint — For bar charts, the color of the section outline. * sectionOutlineStroke — For bar charts, the stroke type for the section outline. * sectionPaint — For bar charts, the color of the section. Usage Description The color component declares a color or gradient than can be referenced when drawing filled shapes. Attributes * color — The color value. For gradient colors, this the starting color. Section 18.1.7.1, “Color Values” * color2 — For gradient colors, this is the color that ends the gradient. * point — The co-ordinates where the gradient color begins. * point2 — The co-ordinates where the gradient color ends. Usage 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 value is the limit of the size of the join. * dash — The dash value sets the dash pattern to be used to draw the line. The space separated integers indicate the length of each alternating drawn and undrawn segments. * dashPhase — The dash phase indicates the offset into the dash pattern that the the line 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 be embedded in a PDF document or displayed as an image on a web page. Note that when used with HTML images, barcodes can not currently display barcode text in the 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 the barcode. * xpos— For PDFs, the absolute y position of the barcode on the page. * ypos— For PDFs, the absolute y position of the barcode on the page. * rotDegrees — For PDFs, the rotation factor of the barcode in degrees. * barHeight — The height of the bars in the barCode * minBarWidth — The minimum bar width. * barMultiplier — The bar multiplier for wide 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 the barcode. * textSize — The size of the barcode text, if any. * altText — The alt text for HTML image links. Usage 18.4. Fill-in-forms If you have a complex, pre-generated PDF with named fields, you can easily fill in the values from you application and present it to the user. Description Defines a form template to populate Attributes * URL — An URL pointing to the PDF file to use as a template. If the value has no protocol part (://), the file is read locally. * filename — The filename to use for the generated PDF file. * exportKey — Place the generated PDF file in a DocumentData object under the specified key in the event context. If set, no redirect will occur. Description Connects a field name to its value Attributes * name — The name of the field * value — The value of the field * readOnly — Should the field be read-only? Defaults to true. 18.5. Rendering Swing/AWT components Seam now provides experimental support for rendering Swing components to into a PDF image. Some Swing look and feels supports, notably ones that use native widgets, will not render correctly. Description Renders a Swing component into a PDF document. Attributes * width — The width of the component to be rendered. * height — ..The height of the component to be rendered. * component — An expression whose value is a Swing or AWT component. Usage 18.6. Configuring iText Document generation works out of the box with no additional configuration needed. However, there are 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. Many browsers (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 resources should be mapped to the DocumentStoreServlet: Document Store Servlet org.jboss.seam.document.DocumentStoreServlet Document Store Servlet *.pdf The use-extensions option on the document store component completes the functionality by instructing the document store to generate URLs with the correct filename extension for the document type being generated. The document store stores documents in conversation scope, and documents will expire when the conversation ends. At that point, references to the document will be invalid. You can specify a default view to be shown when a document does not exist using the error-page property of the documentStore. 18.7. Further documentation For further information on iText, see: * iText Home Page * iText in Action Chapter 19. The Microsoft® Excel® spreadsheet application 19.1. The Microsoft® Excel® spreadsheet application support 19.2. Creating a simple workbook 19.3. Workbooks 19.4. Worksheets 19.5. Columns 19.6. Cells 19.6.1. Validation 19.6.2. Format masks 19.7. Formulas 19.8. Images 19.9. Hyperlinks 19.10. Headers and footers 19.11. Print areas and titles 19.12. Worksheet Commands 19.12.1. Grouping 19.12.2. Page breaks 19.12.3. Merging 19.13. Datatable exporter 19.14. Fonts and layout 19.14.1. Stylesheet links 19.14.2. Fonts 19.14.3. Borders 19.14.4. Background 19.14.5. Column settings 19.14.6. Cell settings 19.14.7. The datatable exporter 19.14.8. Layout examples 19.14.9. Limitations 19.15. Links and further documentation Seam also supports generation of the Microsoft® Excel® spreadsheet application spreadsheets through the excellent JExcelAPI library. The generated document is compatible with the Microsoft® Excel® spreadsheet application versions 95, 97, 2000, XP and 2003. Currently a limited subset of the library functionality is exposed but the ultimate goal is to be able to do everything the library allows for. Please refer to the JExcelAPI documentation for more information on capabilities and limitations. 19.1. The Microsoft® Excel® spreadsheet application support The Microsoft® Excel® spreadsheet application jboss-seam-excel.jar. This JAR contains the the Microsoft® Excel® spreadsheet application JSF controls, which are used to construct views that can render the document, and the DocumentStore component, which serves the rendered document to the user. To include the Microsoft® Excel® spreadsheet application support in your application, included jboss-seam-excel.jar in your WEB-INF/lib directory along with the jxl.jar JAR file. Furthermore, you need to configure the DocumentStore servlet in your web.xml The Microsoft® Excel® spreadsheet application Seam module requires the use of Facelets as the view technology. Additionally, it requires the use of the seam-ui package. The examples/excel project contains an example of the Microsoft® Excel® spreadsheet application support in action. It demonstrates proper deployment packaging, and it shows the exposed functionality. Customizing the module to support other kinds of the Microsoft® Excel® spreadsheet application spreadsheet API's has been made very easy. Implement the ExcelWorkbook interface, and register in components.xml. myExcelExporter my.excel.exporter.ExcelExport and register the excel namespace in the components tag with xmlns:excel="http://jboss.com/products/seam/excel" Then set the UIWorkbook type to myExcelExporter and your own exporter will be used. Default is "jxl", but support for CSV has also been added, using the type "csv". See Section 18.6, “Configuring iText” for information on how to configure the document servlet for serving the documents with an .xls extension. If you are having problems accessing the generated file under IE (especially with https), make sure you are not using too strict restrictions in the browser (see http://www.nwnetworks.com/iezones.htm/), too strict security constraint in web.xml or a combination of both. 19.2. Creating a simple workbook Basic usage of the worksheet support is simple; it is used like a familiar and you can bind to a List, Set, Map, Array or DataModel. That's not terribly useful, so lets have a look at a more common case: First we have the top-level workbook element which serves as the container and it doesn't have any attributes. The child-element worksheet has two attributes; value="#{data}" is the EL-binding to the data and var="item" is the name of the current item. Nested inside the worksheet is a single column and within it you see the cell which is the final bind to the data within the currently iterated item This is all you know to get started dumping your data to worksheets! 19.3. Workbooks Workbooks are the top-level parents of worksheets and stylesheet links. Attributes * type —Defines which export module to be used. The value is a string and can be either "jxl" or "csv". The default is "jxl". * templateURI —A template that should be used as a basis for the workbook. The value is a string (URI). * arrayGrowSize —The amount of memory by which to increase the amount of memory allocated to storing the workbook data. For processeses reading many small workbooks inside a WAS it might be necessary to reduce the default size Default value is 1 megabyte. The value is a number (bytes). * autoFilterDisabled —Should autofiltering be disabled?. The value is a boolean. * cellValidationDisabled —Shoule cell validation be ignored? The value is a boolean. * characterSet —The character set. This is only used when the spreadsheet is read, and has no effect when the spreadsheet is written. The value is a string (character set encoding). * drawingsDisabled —Should drawings be disabled? The value is a boolean. * excelDisplayLanguage —The language in which the generated file will display. The value is a string (two character ISO 3166 country code). * excelRegionalSettings —The regional settings for the generated excel file. The value is a string (two character ISO 3166 country code). * formulaAdjust —Should formulas be adjusted? The value is a boolean. * gcDisabled —Should garbage collection be disabled? The value is a boolean. * ignoreBlanks —Should blanks be ignored? The value is a boolean. * initialFileSize —The initial amount of memory allocated to store the workbook data when reading a worksheet. For processeses reading many small workbooks inside a WAS it might be necessary to reduce the default size Default value is 5 megabytes. The value is a number (bytes). * locale —The locale used by JExcelApi to generate the spreadsheet. Setting this value has no effect on the language or region of the generated excel file. The value is a string. * mergedCellCheckingDisabled —Should merged cell checking be disabled? The value is a boolean. * namesDisabled —Should handling of names be disabled? The value is a boolean. * propertySets —Should any property sets be enabled (such as macros) to be copied along with the workbook? Leaving this feature enabled will result in the JXL process using more memory. The value is a boolean. * rationalization —Should the cell formats be rationalized before writing out the sheet? The value is a boolean. Default is true. * supressWarnings —Should warnings be suppressed?. Due to the change in logging in version 2.4, this will now set the warning behaviour across the JVM (depending on the type of logger used). The value is a boolean. * temporaryFileDuringWriteDirectory —Used in conjunction with the useTemporaryFileDuringWrite setting to set the target directory for the temporary files. This value can be NULL, in which case the normal system default temporary directory is used instead. The value is a string (the directory to which temporary files should be written). * useTemporaryFileDuringWrite —Should a temporary file is used during the generation of the workbook. If not set, the workbook will take place entirely in memory. Setting this flag involves an assessment of the trade-offs between memory usage and performance. The value is a boolean. * workbookProtected —Should the workbook be protected? The value is a boolean. * filename —The filename to use for the download. The value is a string. Please not that if you map the DocumentServlet to some pattern, this file extension must also match. * exportKey —A key under which to store the resulting data in a DocumentData object under the event scope. If used, there is no redirection. Child elemenents * —Zero or more stylesheet links (see Section 19.14.1, “Stylesheet links” ). * —Zero or more worksheets (see Section 19.4, “Worksheets” ). Facets * none defines a workbook with a worksheet and a greeting at A1 19.4. Worksheets Worksheets are the children of workbooks and the parent of columns and worksheet commands They can also contain explicitly placed cells, formulas, images and hyperlinks. They are the pages that make up the workbook. * value —An EL-expression to the backing data. The value is a string. The target of this expression is examined for an Iterable. Note that if the target is a Map, the iteration is done over the Map.Entry entrySet(), so you should use a .key or .value to target in your references. * var —The current row iterator variable name that can later be referenced in cell value attributes. The value is a string * name —The name of the worksheet. The valus is a string. Defaults to Sheet# where # is the worksheet index. If the given worksheet name exists, that sheet is selected. This can be used for merging several data sets into a single worksheet, just define the same name for them (using startRow and startCol to make sure that they don't occupy the same space). * startRow —Defines the starting row for the data. The value is a number. Used for placing the data in other places than the upper-left corner (especially useful if having multiple data sets for a single worksheet). The defaults is 0. * startColumn —Defines the starting column for the data. The value is a number. Used for placing the data in other places than the upper-left corner (especially useful if having multiple data sets for a single worksheet). The default is 0. * automaticFormulaCalculation —Should formulas be automatically calculated? The value is a boolean. * bottomMargin —The bottom margin. The value is a number (inches) * copies —The number of copies. The value is a number. * defaultColumnWidth —The default column width. The value is a number (characters * 256). * defaultRowHeight —The default row height. The value is a number (1/20ths of a point). * displayZeroValues —Should zero-values be displayed? The value is a boolean. * fitHeight —The number of pages vertically that this sheet will be printed into. The value is a number. * fitToPages —Should printing be fit to pages? The value is a boolean. * fitWidth —The number of pages widthwise which this sheet should be printed into. The value is a number. * footerMargin —The margin for any page footer. The value is a number (inches). * headerMargin —The margin for any page headers. The value is a number (inches). * hidden —Should the worksheet be hidden? The value is a boolean. * horizontalCentre —Should the worksheet be centered horizontally? The value is a boolean. * horizontalFreeze —The row at which the pane is frozen vertically. The value is a number. * horizontalPrintResolution —The horizontal print resolution. The value is a number. * leftMargin —The left margin. The value is a number (inches). * normalMagnification —The normal magnificaton factor (not zoom or scale factor). The value is a number (percentage). * orientation —The paper orientation for printing this sheet. The value is a string that can be either "landscape" or "portrait". * pageBreakPreviewMagnification —The page break preview magnificaton factor (not zoom or scale factors). the value is a number (percentage). * pageBreakPreviewMode —Show page in preview mode? The value is a boolean. * pageStart —The page number at which to commence printing. The value is a number. * paperSize —The paper size to be used when printing this sheet. The value is a string that can be one of "a4", "a3", "letter", "legal" etc (see jxl.format.PaperSize ). * password —The password for this sheet. The value is a string. * passwordHash —The password hash - used only when copying sheets. The value is a string. * printGridLines —Should grid lines be printed? The value is a boolean. * printHeaders —Should headers be printed? The value is a boolean. * sheetProtected —Should the sheet be protected (read-only)? The value is a boolean. * recalculateFormulasBeforeSave —Should the formulas be re-calculated when the sheet is saved? The value is a boolean. false * rightMargin —The right margin. The value is a number (inches). * scaleFactor —The scale factor for this sheet to be used when printing. The value is a number (percent). * selected —Should the sheet be selected when the workbook opens? The value is a boolean. * showGridLines —Should gridlines be shown? The value is a boolean. * topMargin —The top margin. The value is a number (inches). * verticalCentre —Center verically? The value is a boolean. * verticalFreeze —The row at which the pane is frozen vertically. The value is a number. * verticalPrintResolution —The vertical print resolution. The value is a number. * zoomFactor —T zoom factor. Do not confuse zoom factor (which relates to the on screen view) with scale factor (which refers to the scale factor when printing). The value is a number (percentage. Child elemenents * —Zero or more print area definitions (see Section 19.11, “Print areas and titles” ). * —Zero or more print title definitions (see Section 19.11, “Print areas and titles” ). * —Zero or more header/footer definitions ((see Section 19.10, “Headers and footers” )). * Zero or more worksheet commands (see Section 19.12, “Worksheet Commands” ). Facets * header—Contents that will be placed at the top of the data block, above the column headers (if any) * footer—Contents that will be placed at the bottom of the data block, below the column footers (if any) defines a worksheet with the name "foo", starting at B2. 19.5. Columns Columns are the children of worksheets and the parents of cells, images, formulas and hyperlinks. They are the structure that control the iteration of the worksheet data. See Section 19.14.5, “Column settings” for formatting. Attributes * none Child elemenents * —Zero or more cells (see Section 19.6, “Cells” ). * —Zero or more formulas (see Section 19.7, “Formulas” ). * —Zero or more images (see Section 19.8, “Images” ). * —Zero or more hyperlinks (see Section 19.9, “Hyperlinks” ). Facets * header —This facet can/will contain one , , or that will be used as header for the column. * footer —This facet can/will contain one , , or that will be used as footer for the column. defines a column with a header and an iterated output 19.6. Cells Cells are nested within columns (for iteration) or inside worksheets (for direct placement using the column and row attributes) and are responsible for outputting the value (usually though en EL-expression involving the var-attribute of the datatable. See ??? Attributes * column —The column where to place the cell. The default is the internal counter. The value is a number. Note that the value is 0-based. * row —The row where to place the cell. The default is the internal counter. The value is number. Note that the value is 0-based. * value —The value to display. Usually an EL-expression referencing the var-attribute of the containing datatable. The value is a string. * comment —A comment to add to the cell. The value is a string. * commentHeight —The height of the comment. The value is a number (in pixels). * commentWidth —A width of the comment. The value is a number (in pixels). Child elemenents * Zero or more validation conditions (see Section 19.6.1, “Validation” ). Facets * none defines a column with a header and an iterated output 19.6.1. Validation Validations are nested inside cells, formulas or cell templates. They add constrains for the cell data. Attributes * value —The limit (or lower limit where applicable) of the validation. The value is a number. * value2 —The upper limit (where applicable) of the validation. The value is a number. * condition —The validation condition. The value is a string. o "equal" - requires the cell value to match the one defined in the value-attribute o "greater_equal" - requires the cell value to be greater than or equal to the value defined in the value-attribute o "less_equal" - requires the cell value to be less than or equal to the value defined in the value-attribute o "less_than" - requires the cell value to be less than the value defined in the value-attribute o "not_equal" - requires the cell value to not match the one defined in the value-attribute o "between" - requires the cell value to be between the values defined in the value- and value2 attributes o "not_between" - requires the cell value not to be between the values defined in the value- and value2 attributes Child elemenents * none Facets * none adds numeric validation to a cell specifying that the value must be between 4 and 18. Attributes * startColumn —The starting column of the range of values to validate against. The value is a number. * startRow —The starting row of the range of values to validate against. The value is a number. * endColumn —The ending column of the range of values to validate against. The value is a number. * endRow —The ending row of the range of values to validate against. The value is a number. Child elemenents * none Facets * none adds validation to a cell specifying that the value must be in the values specified in range A1:A10. Attributes * none Child elemenents * Zero or more list validation items. Facets * none e:listValidation is a just a container for holding multiple e:listValidationItem tags. Attributes * value —A values to validate against. Child elemenents * none Facets * none adds validation to a cell specifying that the value must be "manager" or "employee". 19.6.2. Format masks Format masks are defined in the mask attribute in cell templates, cells or formulas. Note that when using templates, the format mask must be placed in the first template to be cascaded since the constructor hierarchy in JExcelAPI used for copying cell formats makes it hard to change the format mask at a later stage. There are two types of format masks, one for numbers and one for dates 19.6.2.1. Number masks When encountering a format mask, first it is checked if it is in internal form, e.g "format1", "accounting_float" and so on (see jxl.write.NumberFormats ). if the mask is not in the list, it is treated as a custom mask (see java.text.DecimalFormat ). e.g "0.00" and automatically converted to the closest match. 19.6.2.2. Date masks When encountering a format mask, first it is checked if it is in internal form, e.g "format1", "format2" and so on (see jxl.write.DecimalFormats ). if the mask is not in the list, it is treated as a custom mask (see java.text.DateFormat )., e.g "dd.MM.yyyy" and automatically converted to the closest match. 19.7. Formulas Formulas are nested within columns (for iteration) or inside worksheets (for direct placement using the column and row attributes) and add calculations or functions to ranges of cells. They are essentially cells, see Section 19.6, “Cells” for available attributes. Note that they can apply templates and have own font definitions etc just as normal cells. The formula of the cell in placed in the value -attribute as a normal the Microsoft® Excel® spreadsheet application notation. Note that when doing cross-sheet formulas, the worksheets must exist before referencing a formula against them. The value is a string. defines an formula in B2 summing cells A1 in worksheets FooSheet and BarSheet 19.8. Images Images are nested within columns (for iteration) or inside worksheets (for direct placement using the startColumn/startRow and rowSpan/columnSpan attributes). The spans are optional and if omitted, the image will be inserted without resizing. Attributes * startColumn —The starting column of the image. The default is the internal counter. The value is a number. Note that the value is 0-based. * startRow —The starting row of the image. The default is the internal counter. The value is a number. Note that the value is 0-based. * columnSpan —The column span of the image. The default is one resulting in the default width of the image. The value is a float. * rowSpan —The row span of the image. The default is the one resulting in the default height of the image. The value is a float. * URI —The URI to the image. The value is a string. Child elemenents * none Facets * none defines an image in A1:E5 based on the given data 19.9. Hyperlinks Hyperlinks are nested within columns (for iteration) or inside worksheets (for direct placement using the startColumn/startRow and endColumn/endRow attributes). They add link navigation to URIs Attributes * startColumn —The starting column of the hyperlink. The default is the internal counter. The value is a number. Note that the value is 0-based. * startRow —The starting row of the hyperlink. The default is the internal counter. The value is a number. Note that the value is 0-based. * endColumn —The ending column of the hyperlink. The default is the internal counter. The value is a number. Note that the value is 0-based. * endRow —The ending row of the hyperlink. The default is the internal counter. The value is a number. Note that the value is 0-based. * URL —The URL to link. The value is a string. * description —The description of the link. The value is a string. Child elemenents * none Facets * none defines a described hyperlink pointing to SFWK in the area A1:E5 19.10. Headers and footers Headers and footers are childrens of worksheets and contain facets which in turn contains a string with commands that are parsed. Attributes * none Child elemenents * none Facets * left —The contents of the left header/footer part. * center —The contents of the center header/footer part. * right —The contents of the right header/footer part. Attributes * none Child elemenents * none Facets * left —The contents of the left header/footer part. * center —The contents of the center header/footer part. * right —The contents of the right header/footer part. The content of the facets is a string that can contain various #-delimited commands as follows: #date# Inserts the current date #page_number# Inserts the current page number #time# Inserts the current time #total_pages# Inserts the total page count #worksheet_name# Inserts the worksheet name #workbook_name# Inserts the workbook name #bold# Toggles bold font, use another #bold# to turn it off #italics# Toggles italic font, use another #italic# to turn it off #underline# Toggles underlining, use another #underline# to turn it off #double_underline# Toggles double underlining, use another #double_underline# to turn it off #outline# Toggles outlined font, use another #outline# to turn it off #shadow# Toggles shadowed font, use another #shadow# to turn it off #strikethrough# Toggles strikethrough font, use another #strikethrough# to turn it off #subscript# Toggles subscripted font, use another #subscript# to turn it off #superscript# Toggles superscript font, use another #superscript# to turn it off #font_name# Sets font name, used like #font_name=Verdana" #font_size# Sets font size, use like #font_size=12# This document was made on #date# and has #total_pages# pages #time# 19.11. Print areas and titles Print areas and titles childrens of worksheets and worksheet templates and provide... print areas and titles. Attributes * firstColumn —The column of the top-left corner of the area. The parameter is a number. Note that the value is 0-based. * firstRow —The row of the top-left corner of the area. The parameter is a number. Note that the value is 0-based. * lastColumn —The column of the bottom-right corner of the area. The parameter is a number. Note that the value is 0-based. * lastRow —The row of the bottom-right corner of the area. The parameter is a number. Note that the value is 0-based. Child elemenents * none Facets * none defines a print title between A1:A10 and a print area between B2:J10. 19.12. Worksheet Commands Worksheet commands are children of workbooks and are usually executed only once. 19.12.1. Grouping Provides grouping of columns and rows. Attributes * startRow —The row to start the grouping at. The value is a number. Note that the value is 0-based. * endRow —The row to end the grouping at. The value is a number. Note that the value is 0-based. * collapse —Should the grouping be collapsed initially? The value is a boolean. Child elements * none Facets * none Attributes * startColumn —The column to start the grouping at. The value is a number. Note that the value is 0-based. * endColumn —The column to end the grouping at. The value is a number. Note that the value is 0-based. * collapse —Should the grouping be collapsed initially? The value is a boolean. Child elements * none Facets * none groups rows 5 trough 10 and columns 5 through 10 so that the rows are initially collapsed (but not the columns). 19.12.2. Page breaks Provides page breaks Attributes * row —The row to break at. The value is a number. Note that the value is 0-based. Child elements * none Facets * none breaks page at row 5. 19.12.3. Merging Provides cell merging Attributes * startRow —The row to start the merging from. The value is a number. Note that the value is 0-based. * startColumn —The column to start the merging from. The value is a number. Note that the value is 0-based. * endRow —The row to end the merging at. The value is a number. Note that the value is 0-based. * endColumn —The column to end the merging at. The value is a number. Note that the value is 0-based. Child elements * none Facets * none merges the cells in the range A1:J10 19.13. Datatable exporter If you prefer to export an existing JSF datatable instead of writing a dedicated XHTML document, this can also be achieved easily by executing the org.jboss.seam.excel.excelExporter.export component, passing in the id of the datatable as an Seam EL parameter. Consider you have a data table ... that you want to view as an Microsoft® Excel® spreadsheet. Place a in the form and you're done. You can of course execute the exporter with a button, s:link or other preferred method. There are also plans for a dedicated export tag that can be placed inside the datatable tag so you won't have to refer to the datatable by ID. See Section 19.14, “Fonts and layout” for formatting. 19.14. Fonts and layout Controlling how the output look is done with a combination of CSSish style attributes and tag attributes. The most common ones (fonts, borders, backgrounds etc) are CSS and some more general settings are in tag attributes. The CSS attributes cascade down from parent to children and within one tag cascades over the CSS classes referenced in the styleClass attributes and finally over the CSS attributes defined in the styleattribute. You can place them pretty much anywhere but e.g. placing a column width setting in a cell nested within that column makes little sense. 19.14.1. Stylesheet links External stylesheets are references with the e:link tag. They are placed as children of the workbook. Attributes * URL —The URL to the stylesheet Child elemenents * none Facets * none References a stylesheet that can be found at /css/excel.css 19.14.2. Fonts This group of XLS-CSS attributes define a font and its attributes xls-font-family The name of the font. Make sure that it's one that is supported by your system. xls-font-size The font size. Use a plain number xls-font-color The color of the font (see jxl.format.Colour ). xls-font-bold Should the font be bold? Valid values are "true" and "false" xls-font-italic Should the font be italic? Valid values are "true" and "false" xls-font-script-style The script style of the font (see jxl.format.ScriptStyle ). xls-font-underline-style The underline style of the font (see jxl.format.UnderlineStyle ). xls-font-struck-out Should the font be struck out? Valid values are "true" and "false" xls-font A shorthand notation for setting all the values. Place the font name last and use tick marks for fonts with spaces in them, e.g. 'Times New Roman'. Use "italic", "bold" and "struckout". Example style="xls-font: red bold italic 22 Verdana" 19.14.3. Borders This group of XLS-CSS attributes define the borders of the cell xls-border-left-color The border color of the left edge of the cell (see jxl.format.Colour ). xls-border-left-line-style The border line style of the left edge of the cell (see jxl.format.LineStyle ). xls-border-left A shorthand for setting line style and color of the left edge of the cell, e.g style="xls-border-left: thick red" xls-border-top-color The border color of the top edge of the cell (see jxl.format.Colour ). xls-border-top-line-style The border line style of the top edge of the cell (see jxl.format.LineStyle ). xls-border-top A shorthand for setting line style and color of the top edge of the cell, e.g style="xls-border-left: red thick" xls-border-right-color The border color of the right edge of the cell (see jxl.format.Colour ). xls-border-right-line-style The border line style of the right edge of the cell (see jxl.format.LineStyle ). xls-border-right A shorthand for setting line style and color of the right edge of the cell, e.g style="xls-border-right: thick red" xls-border-bottom-color The border color of the bottom edge of the cell (see jxl.format.Colour ). xls-border-bottom-line-style The border line style of the bottom edge of the cell (see jxl.format.LineStyle ). xls-border-bottom A shorthand for setting line style and color of the bottom edge of the cell, e.g style="xls-border-bottom: thick red" xls-border A shorthand for setting line style and color for all edges of the cell, e.g style="xls-border: thick red" 19.14.4. Background This group of XLS-CSS attributes define the background of the cell xls-background-color The color of the background (see jxl.format.LineStyle ). xls-background-pattern The pattern of the background (see jxl.format.Pattern ). xls-background A shorthand for setting the background color and pattern. See above for rules. 19.14.5. Column settings This group of XLS-CSS attributes define the column widths etc. xls-column-width The width of the column. Use largeish values (~5000) to start with. Used by the e:column in xhtml mode. xls-column-widths The width of the column. Use largeish values (~5000) to start with. Used by the excel exporter, placed in the datatable style attribute. Use numerical values or * to bypass a column. Example style="xls-column-widths: 5000, 5000, *, 10000" xls-column-autosize Should an attempt be made to autosize the column? Valid values are "true" and "false". xls-column-hidden Should the column be hidden? Valid values are "true" and "false". 19.14.6. Cell settings This group of XLS-CSS attributes define the cell properties xls-alignment The alignment of the cell value (see jxl.format.Alignment ). xls-force-type The forced type of the cell data. The value is a string that can be one of "general", "number", "text", "date", "formula" or "bool". The type is automatically detected so there is rarely any use for this attribute. xls-format-mask The format mask of the cell, see Section 19.6.2, “Format masks” xls-indentation The indentation of the cell value. The value is numeric. xls-locked Should the cell be locked. Use with workbook level locked. Valid values are "true" and "false". xls-orientation The orientation of the cell value (see jxl.format.Orientation ). xls-vertical-alignment The vertical alignment of the cell value (see jxl.format.VerticalAlignment ). xls-shrink-to-fit Should the cell values shrink to fit? Valid values are "true" and "false". xls-wrap Should the cell wrap with newlines? Valid values are "true" and "false". 19.14.7. The datatable exporter The datatable exporter uses the same xls-css attributes as the xhtml document with the exception that column widths are defined with the xls-column-widths attribute on the datatable (since the UIColumn doesn't support the style or styleClass attributes). 19.14.8. Layout examples TODO 19.14.9. Limitations In the current version there are some known limitations regarding CSS support * When using .xhtml documents, stylesheets must be referenced through the tag * When using the datatable exporter, CSS must be entered through style-attributes, external stylesheets are not supported 19.15. Links and further documentation The core of the the Microsoft® Excel® spreadsheet application functionality is based on the excellent JExcelAPI library which can be found on http://jexcelapi.sourceforge.net/ and most features and possible limitations are inherited from here. If you use the forum or mailing list, please remember that they don't know anything about Seam and the usage of their library, any issues are best reported in the JBoss Seam JIRA under the "excel" module. Chapter 20. RSS support 20.1. Installation 20.2. Generating feeds 20.3. Feeds 20.4. Entries 20.5. Links and further documentation It is now easy to integrate RSS feeds in Seam through the YARFRAW library. The RSS support is currently in the state of "tech preview" in the current release. 20.1. Installation To enable RSS support, include the jboss-seam-rss.jar in your applications WEB-INF/lib directory. The RSS library also has some dependent libraries that should be placed in the same directory. See Section 40.2.6, “Seam RSS support” for a list of libraries to include. The Seam RSS support requires the use of Facelets as the view technology. 20.2. Generating feeds The examples/rss project contains an example of RSS support in action. It demonstrates proper deployment packaging, and it shows the exposed functionality. A feed is a xhtml-page that consist of a feed and a list of nested entry items. 20.3. Feeds Feeds are the top-level entities that describe the properties of the information source. It contains zero or more nested entries. Attributes * uid —An optional unique feed id. The value is a string. * title —The title of the feed. The value is a string. * subtitle —The subtitle of the feed. The value is a string. * updated —When was the feed updated? The value is a date. * link —The link to the source of the information. The value is a string. * feedFormat —The feed format. The value is a string and defaults to ATOM1. Valid values are RSS10, RSS20, ATOM03 and ATOM10. Child elemenents * Zero or more feed entries Facets * none 20.4. Entries Entries are the "headlines" in the feed. Attributes * uid —An optional unique entry id. The value is a string. * title —The title of the entry. The value is a string. * link —A link to the item. The value is a string. * author —The author of the story. The value is a string. * summary —The body of the story. The value is a string. * textFormat —The format of the body and title of the story. The value is a string and valid values are "text" and "html". Defaults to "html". * published —When was the story first published? The value is a date. * updated —When was the story updated? The value is a date. Child elemenents * none Facets * none 20.5. Links and further documentation The core of the RSs functionality is based on the YARFRAW library which can be found on http://yarfraw.sourceforge.net/ and most features and possible limitations are inherited from here. For details on the ATOM 1.0 format, have a look at the specs For details on the RSS 2.0 format, have a look at the specs Chapter 21. Email 21.1. Creating a message 21.1.1. Attachments 21.1.2. HTML/Text alternative part 21.1.3. Multiple recipients 21.1.4. Multiple messages 21.1.5. Templating 21.1.6. Internationalisation 21.1.7. Other Headers 21.2. Receiving emails 21.3. Configuration 21.3.1. mailSession 21.4. Meldware 21.5. Tags Seam now includes an optional components for templating and sending emails. Email support is provided by jboss-seam-mail.jar. This JAR contains the mail JSF controls, which are used to construct emails, and the mailSession manager component. The examples/mail project contains an example of the email support in action. It demonstrates proper packaging, and it contains a number of example that demonstrate the key features currently supported. You can also test your mail's using Seam's integration testing environment. See Section 35.3.4, “Integration Testing Seam Mail”. 21.1. Creating a message You don't need to learn a whole new templating language to use Seam Mail — an email is just facelet! #{person.address} Try out Seam!

,

You can try out Seam by visiting http://labs.jboss.com/jbossseam.

Regards,

Pete

The tag wraps the whole message, and tells Seam to start rendering an email. Inside the tag we use an tag to set who the message is from, a tag to specify a sender (notice how we use EL as we would in a normal facelet), and a tag. The tag wraps the body of the email. You can use regular HTML tags inside the body as well as JSF components. So, now you have your email template, how do you go about sending it? Well, at the end of rendering the m:message the mailSession is called to send the email, so all you have to do is ask Seam to render the view: @In(create=true) private Renderer renderer; public void send() { try { renderer.render("/simple.xhtml"); facesMessages.add("Email sent successfully"); } catch (Exception e) { facesMessages.add("Email sending failed: " + e.getMessage()); } } If, for example, you entered an invalid email address, then an exception would be thrown, which is caught and then displayed to the user. 21.1.1. Attachments Seam makes it easy to attach files to an email. It supports most of the standard java types used when working 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 fileName attribute: You could also attach a java.io.File, a java.net.URL: Or a byte[] or a java.io.InputStream: You'll notice that for a byte[] and a java.io.InputStream you need to specify the MIME type of the attachment (as that information is not carried as part of the file). And it gets even better, you can attach a Seam generated PDF, or any standard JSF view, just by wrapping a around the normal tags you would use: A very tiny PDF If you had a set of files you wanted to attach (for example a set of pictures loaded from a database) you can just use a : 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 src for your image, the attachments will be looked at when trying to locate the image (the Content-ID's must match) — magic! You must declare the attachment before trying to access the status object. 21.1.2. HTML/Text alternative part Whilst most mail readers nowadays support HTML, some don't, so you can add a plain text alternative to your email body: Sorry, your email reader can't show our fancy email, please go to http://labs.jboss.com/jbossseam to explore Seam. 21.1.3. Multiple recipients Often you'll want to send an email to a group of recipients (for example your users). All of the recipient mail tags can be placed inside a : 21.1.4. Multiple messages Sometimes, however, you need to send a slightly different message to each recipient (e.g. a password reset). The best way to do this is to place the whole message inside a : #{person.address} #{p.address} ... 21.1.5. Templating The mail templating example shows that facelets templating Just Works with the Seam mail tags. Our template.xhtml contains: #{person.address} #{subject} This is the default body, specified by the template. Our templating.xhtml contains:

This example demonstrates that you can easily use facelets templating in email!

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 isn't reliable when using Seam Mail (if you send your mail asynchrounously Seam Mail doesn't have access to the full JSF or Servlet context, and so doesn't know about web.xml configuration parameters). If you do need more configure Facelets or JSF when sending mail, you'll need to override the Renderer component and do the configuration programmatically - only for advanced users! 21.1.6. Internationalisation Seam supports sending internationalised 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'll need to make sure facelets uses the correct charset for parsing your pages by setting encoding of the template: 21.1.7. Other Headers Sometimes you'll want to add other headers to your email. Seam provides support for some (see Section 21.5, “Tags”). For example, we can set the importance of the email, and ask for a read receipt: Otherise you can add any header to the message using the tag: 21.2. Receiving emails If you are using EJB then you can use a MDB (Message Driven Bean) to receive email. JBoss provides a JCA adaptor — mail-ra.rar — but the version distributed with JBoss AS has a number of limitations (and isn't bundled in some versions) therefore we recommend using the mail-ra.rar distributed with Seam is recommended (it's in the extras/ directory in the Seam bundle). mail-ra.rar should be placed in $JBOSS_HOME/server/default/deploy; if the version of JBoss AS you use already has this file, replace it. You can configure it like this: @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; public void onMessage(Message message) { // Process the message orderProcessor.process(message.getSubject()); } } Each message received will cause onMessage(Message message) to be called. Most Seam annotations will work inside a MDB but you musn't access the persistence context. You can find more information onmail-ra.rar at http://wiki.jboss.org/wiki/Wiki.jsp?page=InboundJavaMail. If you aren't using JBoss AS you can still use mail-ra.rar or you may find your application server includes a similar adapter. 21.3. Configuration To include Email support in your application, include jboss-seam-mail.jar in your WEB-INF/lib directory. If you are using JBoss AS there is no further configuration needed to use Seam's email support. Otherwise you need to make sure you have the JavaMail API, an implementation of the JavaMail API present (the API and impl used in JBoss AS are distributed with seam as lib/mail.jar), and a copy of the Java Activation Framework (distributed with Seam as lib/activation.jar. Note The Seam Email module requires the use of Facelets as the view technology. Future versions of the library 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 'real' SMTP server. 21.3.1. mailSession A JavaMail Session may be available via a JNDI lookup if you are working in an JEE environment or you can use a Seam configured Session. The mailSession component's properties are described in more detail in Section 31.8, “Mail-related components”. 21.3.1.1. JNDI lookup in JBoss AS The JBossAS deploy/mail-service.xml configures a JavaMail session 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. 21.3.1.2. Seam configured Session A mail session can be configured via components.xml. Here we tell Seam to use smtp.example.com as the smtp server: 21.4. Meldware Seam's mail examples use Meldware (from buni.org) as a mail server. Meldware is a groupware package that provides SMTP, POP3, IMAP, webmail, a shared calendar and an graphical admin tool; it's written as a JEE application so can be deployed onto JBoss AS alongside your Seam application. Caution The version of Meldware distributed with Seam (downloaded on demand) is specially tailored for development - mailboxes, users and aliases (email addresses) are created every time the application deploys. If you want to use Meldware in production you should install the latest release from buni.org. 21.5. 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 tag prepares Seam to generate an email. The standard templating tags of facelets can be used as normal. Inside the body you can use any JSF tag; if it requires access to external resources (stylesheets, javascript) then be sure to set the urlBase. Root tag of a mail message * importance — low, normal or high. By default normal, this sets the importance of the mail message. * 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 use components such as in your emails. * messageId — Sets the Message-ID explicitly Set's 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. Set's 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. Add a recipient to the email. Use multiple tags for multiple recipients. This tag can be safely placed inside a repeat tag such as . * name — the name of the recipient. * address — the email address of the recipient. Add a cc recipient to the email. Use multiple tags for multiple ccs. This tag can be safely placed inside a iterator tag such as . * name — the name of the recipient. * address — the email address of the recipient. Add a bcc recipient to the email. Use multiple tags for multiple bccs. This tag can be safely placed inside a repeat tag such as . * name — the name of the recipient. * address — the email address of the recipient. Add a header to the email (e.g. X-Sent-From: JBoss Seam) * name — The name of the header to add (e.g. X-Sent-From). * value — The value of the header to add (e.g. JBoss Seam). Add an attachment to the email. * value — The file to attach: o String — A String is interpreted as a path to file within the classpath o java.io.File — An EL expression can reference a File object o java.net.URL — An EL expression can reference a URL object o java.io.InputStream — An EL expression can reference an InputStream. In this case both a fileName and a contentType must be specified. o byte[] — An EL expression can reference an byte[]. In this case both a fileName and a contentType must be specified. If the value attribute is ommitted: o If this tag contains a tag, the document described will be generated and attached to the email. A fileName should be specfied. o If this tag contains other JSF tags a HTML document will be generated from them and attached to the email. A fileName should be specfied. * fileName — Specify the file name to use for the attached file. * contentType — Specify the MIME type of the attached file Set's the subject for the email. Set's the body for the email. Supports an alternative facet which, if an HTML email is generated can 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 is generated. Асинхронность и обмен сообщениями 22.1. Асинхронность 22.1.1. Асинхронные методы 22.1.2. Асинхронные методы с диспетчером Quartz 22.1.3. Асинхронные события 22.1.4. Обработка исключений из асинхронных вызовов 22.2. Обмен сообщениями в Seam 22.2.1. Конфигурация 22.2.2. Передача сообщений 22.2.3. Прием сообщений используя компоненты управляемые сообщениями 22.2.4. Прием сообщений клиентом Seam делает очень простой асинхронную работу из вэб запросов. Большинство людей думая об асинхронности в Java EE, думают об использовании JMS. Это безусловно один из путей решения проблемы в Seam и это правильный путь, когда у Вас имеются строгие и четко определенные требования к качеству сервиса. Seam делает легким прием и передачу JMS сообщений используя Seam компоненты. Но для многих случаев использования - JMS убийственна. Seam предоставляет простые асинхронные методы и события для выбираемых Вами диспетчеров: * java.util.concurrent.ScheduledThreadPoolExecutor (по умолчанию) EJB служба времени (для EJB 3.0 средств) Quartz 22.1. Асинхронность Асинхронные события и вызовы методов имеют такое качество сервиса ожидания, как и основной механизм диспетчера. Заданный по умолчанию диспетчер, основанный на классе ScheduledThreadPoolExecutor, выполняется эффективно, но не предоставляет поддержки для постоянных асинхронных задач, и следовательно не дает гарантии, что задача будет когда-либо выполнена. Если Вы работаете в среде EJB 3.0, добавьте следующую строку в файл components.xml: тогда Ваши асинхронные задания будут обработаны сервисом таймера среды EJB. Если Вы не знакомы с сервисом таймера, не волнуйтесь, Вам не надо непосредственно взаимодействовать с ним, если будете использовать асинхронные методы Seam. Важно знать, что любая хорошая реализация среды EJB 3.0, имеет возможность использовать стойкий таймер, который предоставляет гарантию, что задачи будут выполнены. В качестве альтернативы можно использовать библиотеку с открытым исходным кодом Quartz, для управления асинхронными методами. Вы должны включить jar-файл библиотеки Quartz в приложение EAR и объявить как Java-модуль в application.xml. Диспетчер Quartz может быть сконфигурирован добавлением файла свойств Quartz в classpath. Это должен быть файл с именем seam.quartz.properties. Кроме того, Вы должны добавить следующую строку в файл components.xml, что бы установить диспетчер Quartz. API Seam для планировщика по умолчанию ScheduledThreadPoolExecutor для EJB3 таймера и для планировщика Quartz в значительной степени одни и те же. Они могут подключиться, добавляя строку в components.xml. 22.1.1. Асинхронные методы В простейшем случае, асинхронный запрос позволяет методу запроса быть обработанным асинхронно (в другом потоке) от вызывающей программы. Обычно мы используем асинхронный запрос, когда хотим вернуть непосредственный ответ клиенту, а саму важную работу выполнить в фоновом режиме. Этот шаблон очень хорошо работает в приложениях, которые используют AJAX, где клиент может автоматически запросить результат работы сервера. Для EJB компонентов, мы в локальном интерфейсе аннотацией определяем асинхронный метод. @Local public interface PaymentHandler { @Asynchronous public void processPayment(Payment payment); } (Для JavaBean компонентов мы можем аннотировать компонент реализующий класс, если это нам нравится) Использование асинхронности прозрачно в классе компонента: @Stateless @Name("paymentHandler") public class PaymentHandlerBean implements PaymentHandler { public void processPayment(Payment payment) { //выполняет некоторую работу! } } И также прозрачна для клиента: @Stateful @Name("paymentAction") public class CreatePaymentAction { @In(create=true) PaymentHandler paymentHandler; @In Bill bill; public String pay() { paymentHandler.processPayment( new Payment(bill) ); return "success"; } } Асинхронный метод полностью обрабатывается в новом контексте событий и не имеет доступа к состояниям контекстов сессии или диалога запускающего процесса. Тем не менее контекст бизнес-процесса доступен. Вызовы асинхронных методов могут быть запланированы на более позднее время, используя аннотации @Duration, @Expiration и @IntervalDuration. @Local public 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; @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"; } } И клиент, и сервер могут иметь доступ к объекту Timer, связанному с запускаемым заданием. Объект Timer показан ниже как EJB3 таймер, когда Вы используете диспетчер EJB3. По умолчанию это - ScheduledThreadPoolExecutor, возвращающий объект Timer. Для диспетчера Quartz, это - QuartzTriggerHandle, который будет обсуждаться в следующей секции. @Local public 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) { //выполняет некоторую работу! return timer; //заметьте, что возвращаемое значение проигнорировано } } @Stateful @Name("paymentAction") public class CreatePaymentAction { @In(create=true) PaymentHandler paymentHandler; @In Bill bill; public String schedulePayment() { Timer timer = paymentHandler.processScheduledPayment( new Payment(bill), bill.getDueDate() ); return "success"; } } Асинхронные методы не могут возвращать никакое другое значение вызывающей программе. 22.1.2. Асинхронные методы с диспетчером Quartz Диспетчер Quartz (смотрите ранее, как установить его) также использует аннотации @Asynchronous, @Duration, @Expiration и @IntervalDuration, как и диспетчер по умолчанию. Но у него имеются некоторые мощные дополнительные возможности. Диспетчер Quartz поддерживает три новые аннотации. Аннотация @FinalExpiration определят конечную дату для повторяющегося задания. Заметьте, что Вы можете сделать "инъекцию" объекта QuartzTriggerHandle. @In QuartzTriggerHandle timer; // Определенние метода в компоненте "процесса" @Asynchronous public QuartzTriggerHandle schedulePayment(@Expiration Date when, @IntervalDuration Long interval, @FinalExpiration Date endDate, Payment payment) { // выполняет повторяющееся или долго выполняющееся задание до endDate } ... ... // Код планируемого задание выполнения бизнес логики // Стартуем теперь, повторяем каждый час и заканчиваем 10-го мая 2010 Calendar cal = Calendar.getInstance (); cal.set (2010, Calendar.MAY, 10); processor.schedulePayment(new Date(), 60*60*1000, cal.getTime(), payment); Заметим, что метод возвращает объект QuartzTriggerHandle, который можно использовать позже, что бы остановить, приостановить или возобновить работу планировщика.Объект QuartzTriggerHandle сериализируемый, так что можно его сохранить в базе данных, если Вы хотите сохранить его для более широкого периода времени. QuartzTriggerHandle handle = processor.schedulePayment(payment.getPaymentDate(), payment.getPaymentCron(), payment); payment.setQuartzTriggerHandle( handle ); // сохраняем объект payment в базе данных // позже ... // возвращаем объект payment из базы данных // прекращаем остающиеся задания планировщика payment.getQuartzTriggerHandle().cancel(); Аннотация @IntervalCron поддерживает синтаксис заданий cron ОС Unix для заданий планировщика. Например, следующий асинхронный метод выполняется в 2:10 и 2:44 после полудня каждую среду марта. // Определение метода @Asynchronous public QuartzTriggerHandle schedulePayment(@Expiration Date when, @IntervalCron String cron, Payment payment) { // выполнение повторяющегося или длительного задания } ... ... // Код планируемого задание выполнения бизнес логики QuartzTriggerHandle handle = processor.schedulePayment(new Date(), "0 10,44 14 ? 3 WED", payment); Аннотация @IntervalBusinessDay поддерживает запуск сценария "энный рабочий день". Например, следующий асинхронный метод запускается в 14:00 во второй рабочий день каждой недели. По умолчанию исключаются все выходные и федеральные праздничные дни США до 2010 года. // определение метода @Asynchronous public QuartzTriggerHandle schedulePayment(@Expiration Date when, @IntervalBusinessDay NthBusinessDay nth, Payment payment) { // выполнение повторяющегося или длительного задания } ... ... // Код планируемого задание выполнения бизнес логики QuartzTriggerHandle handle = processor.schedulePayment(new Date(), new NthBusinessDay(2, "14:00", WEEKLY), payment); Объект NthBusinessDay содержит конфигурацию "пускового" триггера. Вы можете специфицировать другие выходные дни (например праздничные дни компании, праздники не США и прочее) через переопределение свойства additionalHolidays. public class NthBusinessDay implements Serializable { int n; String fireAtTime; List additionalHolidays; BusinessDayIntervalType interval; boolean excludeWeekends; boolean excludeUsFederalHolidays; public enum BusinessDayIntervalType { WEEKLY, MONTHLY, YEARLY } public NthBusinessDay () { n = 1; fireAtTime = "12:00"; additionalHolidays = new ArrayList (); interval = BusinessDayIntervalType.WEEKLY; excludeWeekends = true; excludeUsFederalHolidays = true; } ... ... } Аннотации @IntervalDuration, @IntervalCron и @IntervalNthBusinessDay взаимоисключающие и если они будут использоваться в одном и том же методе, то возникнет исключение RuntimeException. 22.1.3. Асинхронные события Управляемые компонентом события могут быть также асинхронными. Чтобы вызвать событие для асинхронного процесса, надо просто вызвать метод raiseAsynchronousEvent() класса Events. Для события времени планировщика, надо вызвать метод raiseTimedEvent(), передав объект планировщик (для диспетчера по умолчанию или диспетчера сервиса таймера, используйте TimerSchedule). Компоненты могут перехватывать асинхронные события обычным способом, но надо помнить, что только бизнес-процесса контекст доступен для асинхронных нитей. 22.1.4. Обработка исключений из асинхронных вызовов Каждый асинхронный диспетчер ведет себя по разному, когда распространяет исключения. Например, диспетчер java.util.concurrent приостановит выполнение последующих повторяющихся вызовов и сервис таймера EJB3 перехватит исключение. Seam перехватывает любое исключение, которое распространяется от асинхронного вызова прежде, чем оно достигнет диспетчера. По умолчанию, любое исключение, которое распространяется от асинхронного исключения отлавливается и фиксируется на уровне ошибок. Вы можете это настроить глобально, переопределяя компонент org.jboss.seam.async.asynchronousExceptionHandler: @Scope(ScopeType.STATELESS) @Name("org.jboss.seam.async.asynchronousExceptionHandler") public class MyAsynchronousExceptionHandler extends AsynchronousExceptionHandler { @Logger Log log; @In Future timer; @Override public void handleException(Exception exception) { log.debug(exception); timer.cancel(false); } } Здесь, например, используя диспетчер java.util.concurrent, мы вводим его управляющие объекты и отменяем все будущие вызовы, если происходит исключение. Вы можете также настроить обработчик для отдельного компонента, реализовав в нем метод handleAsynchronousException(Exception exception). Например: public void handleAsynchronousException(Exception exception) { log.fatal(exception); } 22.2. Messaging in Seam Seam makes it easy to send and receive JMS messages to and from Seam components. 22.2.1. Configuration To configure Seam's infrastructure for sending JMS messages, you need to tell Seam about any topics and 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 with JBossMQ. 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: 22.2.2. Sending messages Now, you can inject a JMS TopicPublisher and TopicSession into any component: @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); } } Or, for working with a queue: @In private QueueSender paymentQueueSender; @In private QueueSession queueSession; public void publish(Payment payment) { try { paymentQueueSender.send( queueSession.createObjectMessage(payment) ); } catch (Exception ex) { throw new RuntimeException(ex); } } 22.2.3. Receiving messages using a message-driven bean You can process messages using any EJB3 message driven bean. Message-driven beans may even be Seam components, in which case it is possible to inject other event and application scoped Seam components. 22.2.4. Receiving messages in the client Seam Remoting lets you subscribe to a JMS topic from client-side JavaScript. This is described in Chapter 25, Remoting. Chapter 23. Caching 23.1. Using Caching in Seam 23.2. Page fragment caching In almost all enterprise applications, the database is the primary bottleneck, and the least scalable tier of the runtime environment. People from a PHP/Ruby environment will try to tell you that so-called "shared nothing" architectures scale well. While that may be literally true, I don't know of many interesting multi-user applications which can be implemented with no sharing of resources between different nodes of the cluster. What these silly people are really thinking of is a "share nothing except for the database" architecture. Of course, sharing the database is the primary problem with scaling a multi-user application—so the claim that this architecture is highly scalable is absurd, and tells you a lot about the kind of applications that these folks spend most of their time working on. Almost anything we can possibly do to share the database less often is worth doing. This calls for a cache. Well, not just one cache. A well designed Seam application will feature a rich, multi-layered caching strategy that impacts every layer of the application: * The database, of course, has its own cache. This is super-important, but can't scale like a cache in the application tier. * Your ORM solution (Hibernate, or some other JPA implementation) has a second-level cache of data from the database. This is a very powerful capability, but is often misused. In a clustered environment, keeping the data in the cache transactionally consistent across the whole cluster, and with the database, is quite expensive. It makes most sense for data which is shared between many users, and is updated rarely. In traditional stateless architectures, people often try to use the second-level cache for conversational state. This is always bad, and is especially wrong in Seam. * The Seam conversation context is a cache of conversational state. Components you put into the 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-managed persistence context associated with a conversation-scoped stateful session bean) acts as a cache of data that has been read in the current conversation. This cache tends to have a pretty high hitrate! Seam optimizes the replication of Seam-managed persistence contexts in a clustered environment, and there is no requirement for transactional consistency with the database (optimistic locking is sufficient) so you don't need to worry too much about the performance implications of this cache, unless you read thousands of objects into a single persistence context. * The application can cache non-transactional state in the Seam application context. State kept in the application context is of course not visible to other nodes in the cluster. * The application can cache transactional state using the Seam cacheProvider component, which integrates JBossCache, JBoss POJO Cache or EHCache into the Seam environment. This state will be visible to other nodes if your cache supports running in a clustered mode. * Finally, Seam lets you cache rendered fragments of a JSF page. Unlike the ORM second-level cache, this cache is not automatically invalidated when data changes, so you need to write application code to perform explicit invalidation, or set appropriate expiration policies. For more information about the second-level cache, you'll need to refer to the documentation of your ORM solution, since this is an extremely complex topic. In this section we'll discuss the use of caching directly, via the cacheProvider component, or as the page fragment cache, via the control. 23.1. Using Caching in Seam The built-in cacheProvider component manages an instance of: JBoss Cache 1.x (suitable for use in JBoss 4.2.x and other containers) org.jboss.cache.TreeCache JBoss Cache 2.x (suitable for use in JBoss 5.x and other containers) org.jboss.cache.Cache JBoss POJO Cache 1.x (suitable for use in JBoss 4.2.x and other containers) org.jboss.cache.aop.PojoCache EHCache (suitable for use in any container) net.sf.ehcache.CacheManager You can safely put any immutable Java object in the cache, and it will be stored in the cache and replicated across the cluster (assuming that replication is supported and enabled). If you want to keep mutable objects in the cache read the documentation of the underling caching project documentation to discover how to notify the cache of changes to the cache. To use cacheProvider, you need to include the jars of the cache implementation in your project: JBoss Cache 1.x * jboss-cache.jar - JBoss Cache 1.4.1 * jgroups.jar - JGroups 2.4.1 JBoss Cache 2.x * jboss-cache.jar - JBoss Cache 2.2.0 * jgroups.jar - JGroups 2.6.2 JBoss POJO Cache 1.x * jboss-cache.jar - JBoss Cache 1.4.1 * jgroups.jar - JGroups 2.4.1 * jboss-aop.jar - JBoss AOP 1.5.0 EHCache * ehcache.jar - EHCache 1.2.3 Tip If you are using JBoss Cache in containers other than JBoss Application Server, look at the JBoss Cache wiki page for more dependencies. For an EAR depoyment of Seam, we recommend that the cache jars and configuration go directly into the EAR. You'll also need to provide a configuration file for JBossCache. Place treecache.xml with an appropriate cache configuration into the classpath (e.g. the ejb jar or WEB-INF/classes). JBossCache has many scary 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. EHCache will run in it's default configuration without a configuration file To alter the configuration file in use, configure your cache in components.xml: Now you can inject the cache into any Seam component: @Name("chatroomUsers") @Scope(ScopeType.STATELESS) public class ChatroomUsers { @In CacheProvider cacheProvider; @Unwrap public Set getUsers() throws CacheException { Set userList = (Set) cacheProvider.get("chatroom", "userList"); if (userList==null) { userList = new HashSet(); cacheProvider.put("chatroom", "userList", userList); } return userList; } } If you want to have multiple cache configurations in your application, use components.xml to configure multiple cache providers: 23.2. Page fragment caching The most interesting use of caching in Seam is the tag, Seam's solution to the problem of page fragment caching in JSF. uses pojoCache internally, so you need to follow the steps listed above before you can use it. (Put the jars in the EAR, wade through the scary configuration options, etc.) is used for caching some rendered content which changes rarely. For example, the welcome page of our blog displays the recent blog entries:

#{blogEntry.title}

The key let's you have multiple cached versions of each page fragment. In this case, there is one cached version per blog. The region determines the cache or region node that all version will be stored in. Different nodes may have different expiry policies. (That's the stuff you set up using the aforementioned scary configuration options.) Of course, the big problem with is that it is too stupid to know when the underlying data changes (for example, when the blogger posts a new entry). So you need to evict the cached fragment manually: public void post() { ... entityManager.persist(blogEntry); cacheProvider.remove("welcomePageFragments", "recentEntries-" + blog.getId() ); } Alternatively, if it is not critical that changes are immediately visible to the user, you could set a short expiry time on the cache node. Chapter 24. Web Services 24.1. Configuration and Packaging 24.2. Conversational Web Services 24.2.1. A Recommended Strategy 24.3. An example web service 24.4. RESTful HTTP webservices with RESTEasy 24.4.1. RESTEasy configuration and request serving 24.4.2. Resources and providers as Seam components Seam integrates with JBossWS to allow standard JEE web services to take full advantage of Seam's contextual framework, including support for conversational web services. This chapter walks through the steps required to allow web services to run within a Seam environment. 24.1. Configuration and Packaging To allow Seam to intercept web service requests so that the necessary Seam contexts can be created for the request, a special SOAP handler must be configured; org.jboss.seam.webservice.SOAPRequestHandler is a SOAPHandler implementation that does 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 the following SOAP handler configuration: Seam WebService Endpoint ##SOAP11_HTTP SOAP Request Handler org.jboss.seam.webservice.SOAPRequestHandler 24.2. Conversational Web Services So how are conversations propagated between web service requests? Seam uses a SOAP header element present in both the SOAP request and response messages to carry the conversation ID from the consumer to the service, and back again. Here's an example of a web service request that contains a conversation ID: 2 As you can see in the above SOAP message, there is a conversationId element within the SOAP header that contains the conversation ID for the request, in this case 2. Unfortunately, because web services may be consumed by a variety of web service clients written in a variety of languages, it is up to the developer to implement conversation ID propagation between individual web services that are intended 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 a namespace of http://www.jboss.org/seam/webservice, otherwise Seam will not be able to read the conversation ID from the request. Here's an example of a response to the above request message: 2 As you can see, the response message contains the same conversationId element as the request. 24.2.1. A Recommended Strategy As web services must be implemented as either a stateless session bean or POJO, it is recommended that for conversational web services, the web service acts as a facade to a conversational Seam component. [Image] If the web service is written as a stateless session bean, then it is also possible to make it a Seam component by giving it a @Name. Doing this allows Seam's bijection (and other) features to be used in the web service class itself. 24.3. An example web service Let's walk through an example web service. The code in this section all comes from the seamBay example application in Seam's /examples directory, and follows the recommended strategy as described in the previous section. Let's first take a look at the web service class and one of its web service methods: @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 } As you can see, our web service is a stateless session bean, and is annotated using the JWS annotations from the javax.jws package, as defined by JSR-181. The @WebService annotation tells the 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 serviceName attributes in the @WebService annotation are optional. As is required by the specification, each method that is to be exposed as a web service method must also be declared in the remote interface of the web service class (when the web service is a stateless session 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 to Seam's built-in Identity component. In keeping with our recommended strategy, the web service is written as a simple facade, passing off the real work to a Seam component. This allows for the greatest reuse of business logic between web services and other clients. Let's look at another example. This web service method begins a new conversation by delegating to the AuctionAction.createAuction() method: @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); } And here's the code from AuctionAction: @Begin public void createAuction() { auction = new Auction(); auction.setAccount(authenticatedAccount); auction.setStatus(Auction.STATUS_UNLISTED); durationDays = DEFAULT_AUCTION_DURATION; } From this we can see how web services can participate in long running conversations, by acting as a facade and delegating the real work to a conversational Seam component. 24.4. RESTful HTTP webservices with RESTEasy Seam integrates the RESTEasy implementation of the JAX-RS specification (JSR 311). You can decide how "deep" the integration into your Seam application is going to be: * Seamless integration of RESTEasy bootstrap and configuration, automatic detection of resources and providers. * Serving HTTP/REST requests with the SeamResourceServlet, no external servlet or configuration in web.xml required. * Writing resources as Seam components, with full Seam lifecycle management and interception (bijection). 24.4.1. RESTEasy configuration and request serving First, get the RESTEasy libraries and the jaxrs-api.jar, deploy them with the other libraries of your application. Also deploy the integration library, jboss-seam-resteasy.jar On startup, all classes annotated @javax.ws.rs.Path will be discovered automatically and registered as HTTP resources. Seam automatically accepts and serves HTTP requests with its built-in SeamResourceServlet. The URI of a resource is build as follows: * The URI starts with the pattern mapped in web.xml for the SeamResourceServlet, e.g /seam/resource if you follow the common examples. Change this setting to expose your RESTful resources under a different base. Note that this is a global change and other Seam resources (e.g. s:graphicImage) are then also served under that base path. * The RESTEasy integration for Seam then appends a configurable string to the base path, by default this is /rest. Hence, the full base path of your resources would e.g. be /seam/resource/rest. We recommend that you change this string in your application, you could for example add a version number to prepare for a future REST API upgrade of your services (old clients would keep the old URI base): /seam/resource/restv1. * Finally, the actual resource is available under the defined @Path, e.g. a resource mapped with @Path("/customer") would be available under /seam/resource/rest/customer. As an example, the following resource definition would return a plaintext representation for any GET requests using the URI http://your.hostname/seam/resource/rest/customer/123: @Path("/customer") public class MyCustomerResource { @GET @Path("/{customerId}") @ProduceMime("text/plain") public String getCustomer(@PathParam("customerId") int id) { return ...; } } No additional configuration is required, you do not have to edit web.xml or any other setting if these defauls are acceptable. However, you can configure RESTEasy in your Seam application. First import the resteasy namespace into your XML configuration file header: You can then change the /rest prefix as mentioned earlier: The full base path to your resources is now /seam/resource/restv1/{resource} - note that your @Path definitions and mappings do NOT change. This is an application-wide switch usually used for versioning of the HTTP API. You can disable stripping of the base path if you'd like to map the full path in your resources: The path of a resource is now mapped with e.g. @Path("/seam/resource/rest/customer"). We do not recommend disabling this feature, as your resource class mappings are then bound to a particular deployment scenario. Seam will scan your classpath for any deployed @javax.ws.rs.Path resources and any @javax.ws.rs.ext.Provider classes. You can disable scanning and configure these classes manually: org.foo.MyCustomerResource org.foo.MyOrderResource org.foo.MyFancyProvider The use-built-in-providers switch enables (default) or disables the RESTEasy built-in providers. We recommend you leave them enabled, as they provide plaintext, JSON, and JAXB marshalling out of the box. Finally, you can configure media type and language URI extensions: txttext/plain deutschde-DE This definition would map the URI suffix of .txt.deutsch to additional Accept and Accept-Language header values text/plain and de-DE. 24.4.2. Resources and providers as Seam components Any resource and provider instances are managed by RESTEasy by default. That means a resource class will be instantiated by RESTEasy and serve a single request, after which it will be destroyed. This is the default JAX-RS lifecycle. Providers are instantiated once for the whole application and are effectively singletons and supposed to be stateless. You can write resources and providers as Seam components and benefit from the richer lifecycle management of Seam, and interception for bijection, security, and so on. Simply make your resource class a Seam component: @Name("customerResource") @Path("/customer") public class MyCustomerResource { @In CustomerDAO customerDAO; @GET @Path("/{customerId}") @ProduceMime("text/plain") public String getCustomer(@PathParam("customerId") int id) { return customerDAO.find(id).getName(); } } An instance of customerResource is now handled by Seam when a request hits the server. This is a Seam JavaBean component that is EVENT-scoped, hence no different than the default JAX-RS lifecycle. However, you get full Seam injection support and all other Seam components and contexts are available to you. Currently also supported are SESSION, APPLICATION, and STATELESS resource components. Remember that any HTTP request has to transmit a valid session identifier (cookie, URI path parameter) for correct handling of the server-side session context. Conversation-scoped resource components and mapping of conversations is currently not supported but will be available soon. Provider classes can also be Seam components, they must be APPLICATION-scoped or STATELESS. Resources and providers can be EJBs or JavaBeans, like any other Seam component. Chapter 25. Remoting 25.1. Configuration 25.2. The "Seam" object 25.2.1. A Hello World example 25.2.2. Seam.Component 25.2.3. Seam.Remoting 25.3. Evaluating EL Expressions 25.4. Client Interfaces 25.5. The Context 25.5.1. Setting and reading the Conversation ID 25.5.2. Remote calls within the current conversation scope 25.6. Batch Requests 25.7. Working with Data types 25.7.1. Primitives / Basic Types 25.7.2. JavaBeans 25.7.3. Dates and Times 25.7.4. Enums 25.7.5. Collections 25.8. Debugging 25.9. Handling Exceptions 25.10. The Loading Message 25.10.1. Changing the message 25.10.2. Hiding the loading message 25.10.3. A Custom Loading Indicator 25.11. Controlling what data is returned 25.11.1. Constraining normal fields 25.11.2. Constraining Maps and Collections 25.11.3. Constraining objects of a specific type 25.11.4. Combining Constraints 25.12. JMS Messaging 25.12.1. Configuration 25.12.2. Subscribing to a JMS Topic 25.12.3. Unsubscribing from a Topic 25.12.4. Tuning the Polling Process Seam 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 no up-front development effort - your components only require simple annotating to become accessible via AJAX. This chapter describes the steps required to build an AJAX-enabled web page, then goes on to explain the features of the Seam Remoting framework in more detail. 25.1. Configuration To use remoting, the Seam Resource servlet must first be configured in your web.xml file: Seam Resource Servlet org.jboss.seam.servlet.SeamResourceServlet Seam Resource Servlet /seam/resource/* The next step is to import the necessary Javascript into your web page. There are a minimum of two scripts that must be imported. The first one contains all the client-side framework code that enables remoting functionality: The second script contains the stubs and type definitions for the components you wish to call. It is generated dynamically based on the local interface of your components, and includes type definitions for all of the classes that can be used to call the remotable methods of the interface. The name of the script reflects the name of your component. For example, if you have a stateless session bean annotated 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 as parameters of your script tag: Alternatively, you may use the s:remote tag to import the required Javascript. Separate each component or class name you wish to import with a comma: 25.2. The "Seam" object Client-side interaction with your components is all performed via the Seam Javascript object. This object is defined in remote.js, and you'll be using it to make asynchronous calls against your component. It is split into two areas of functionality; Seam.Component contains methods for working with components and Seam.Remoting contains methods for executing remote requests. The easiest way to become familiar with this object is to start with a simple example. 25.2.1. A Hello World example Let's step through a simple example to see how the Seam object works. First of all, let's create a new Seam component called helloAction. @Stateless @Name("helloAction") public class HelloAction implements HelloLocal { public String sayHello(String name) { return "Hello, " + name; } } You also need to create a local interface for our new component - take special note of the @WebRemote annotation, as it's required to make our method accessible via remoting: @Local public interface HelloLocal { @WebRemote public String sayHello(String name); } That's all the server-side code we need to write. Now for our web page - create a new page and import the helloAction component: To make this a fully interactive user experience, let's add a button to our page: We'll also need to add some more script to make our button actually do something when it's clicked: We're done! Deploy your application and browse to your page. Click the button, and enter a name when prompted. A message box will display the hello message confirming that the call was successful. If you want 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's 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 method is responsible for prompting the user for their name and then making a remote request. Take a look at the following line: Seam.Component.getInstance("helloAction").sayHello(name, sayHelloCallback); The first section of this line, Seam.Component.getInstance("helloAction") returns a proxy, or "stub" 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 isn't a parameter of our component's sayHello method, instead it tells the Seam Remoting framework that once it receives the response to our request, it should pass it to the sayHelloCallback Javascript method. This callback 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 an alert message displaying the result of our method call. 25.2.2. Seam.Component The Seam.Component Javascript object provides a number of client-side methods for working with your Seam components. The two main methods, newInstance() and getInstance() are documented in the following sections however their main difference is that newInstance() will always create a new instance of a component type, and getInstance() will return a singleton instance. 25.2.2.1. Seam.Component.newInstance() Use this method to create a new instance of an entity or Javabean component. The object returned by this method will have the same getter/setter methods as its server-side counterpart, or alternatively if you wish you can access its fields directly. Take the following Seam entity component for example: @Name("customer") @Entity public class Customer implements Serializable { private Integer customerId; private String firstName; private String lastName; @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; } } To create a client-side Customer you would write the following code: var customer = Seam.Component.newInstance("customer"); Then from here you can set the fields of the customer object: customer.setFirstName("John"); // Or you can set the fields directly customer.lastName = "Smith"; 25.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 a singleton for the specified component, so calling it twice in a row with the same component name will return 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: Seam.Component.getInstance("customerAction").saveCustomer(customer); 25.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 is not. if (Seam.Component.getComponentName(instance) == "customer") alert("Customer"); else if (Seam.Component.getComponentName(instance) == "staff") alert("Staff member"); 25.2.3. Seam.Remoting Most of the client side functionality for Seam Remoting is contained within the Seam.Remoting object. While you shouldn't need to directly call most of its methods, there are a couple of important ones worth mentioning. 25.2.3.1. Seam.Remoting.createType() If your application contains or uses Javabean classes that aren't Seam components, you may need to create 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 name as a parameter: var widget = Seam.Remoting.createType("com.acme.widgets.MyWidget"); 25.2.3.2. Seam.Remoting.getTypeName() This method is the equivalent of Seam.Component.getComponentName() but for non-component types. It will return the name of the type for an object instance, or null if the type is not known. The name is the fully qualified name of the type's Java class. 25.3. Evaluating EL Expressions Seam Remoting also supports the evaluation of EL expressions, which provides another convenient method for retrieving data from the server. Using the Seam.Remoting.eval() function, an EL expression can be remotely evaluated on the server and the resulting value returned to a client-side callback 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 an example: function customersCallback(customers) { for (var i = 0; i < customers.length; i++) { alert("Got customer: " + customers[i].getName()); } } Seam.Remoting.eval("#{customers}", customersCallback); 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 is important 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 is required to import the customer type: 25.4. Client Interfaces In the configuration section above, the interface, or "stub" for our component is imported into our page either 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 other components or types that are required to execute the methods of our component are generated and made available for the remoting framework to use. There are two types of client stub that can be generated, "executable" stubs and "type" stubs. Executable stubs are behavioural, and are used to execute methods against your session bean components, while type stubs contain state and represent the types that can be passed in as parameters or returned as a result. The type of client stub that is generated depends on the type of your Seam component. If the component is a session bean, then an executable stub will be generated, otherwise if it's an entity or JavaBean, then a type stub will be generated. There is one exception to this rule; if your component is a 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 to use remoting to call methods of your JavaBean components in a non-EJB environment where you don't have access to session beans. 25.5. The Context The Seam Remoting Context contains additional information which is sent and received as part of a remoting request/response cycle. At this stage it only contains the conversation ID but may be expanded in the future. 25.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 read or set the conversation ID in the Seam Remoting Context. To read the conversation ID after making a remote request call Seam.Remoting.getContext().getConversationId(). To set the conversation ID before making a request, call Seam.Remoting.getContext().setConversationId(). If the conversation ID hasn't been explicitly set with Seam.Remoting.getContext().setConversationId(), then it will be automatically assigned the first valid conversation ID that is returned by any remoting call. If you are working with multiple conversations within your page, then you may need to explicitly set the conversation ID before each call. If you are working with just a single conversation, then you don't need to do anything special. 25.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's conversation. To do this, you must explicitly set the conversation ID to that of the view before making the remote call. This small snippet of JavaScript will set the conversation ID that is used for remoting calls to the current view's conversation ID: Seam.Remoting.getContext().setConversationId( #{conversation.id} ); 25.6. Batch Requests Seam Remoting allows multiple component calls to be executed within a single request. It is recommended 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 calls executed after starting a batch are queued, rather than being sent immediately. When all the desired component calls have been added to the batch, the Seam.Remoting.executeBatch() method will send a single request containing all of the queued calls to the server, where they will be executed in order. After the calls have been executed, a single response containining all return values will be returned 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 don't want to send it, the Seam.Remoting.cancelBatch() method will discard any calls that were queued and exit the batch mode. To see an example of a batch being used, take a look at /examples/remoting/chatroom. 25.7. Working with Data types 25.7.1. Primitives / Basic Types This section describes the support for basic data types. On the server side these values are generally compatible with either their primitive type or their corresponding wrapper class. 25.7.1.1. String Simply use Javascript String objects when setting String parameter values. 25.7.1.2. Number There is support for all number types supported by Java. On the client side, number values are always serialized as their String representation and then on the server side they are converted to the correct destination type. Conversion into either a primitive or wrapper type is supported for Byte, Double, Float, Integer, Long and Short types. 25.7.1.3. Boolean Booleans are represented client side by Javascript Boolean values, and server side by a Java boolean. 25.7.2. JavaBeans In general these will be either Seam entity or JavaBean components, or some other non-component class. Use the appropriate method (either Seam.Component.newInstance() for Seam components or 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 used as parameter values, where the parameter is not one of the other valid types mentioned anywhere else in this section. In some situations you may have a component method where the exact parameter type cannot be determined, such as: @Name("myAction") public class MyAction implements MyActionLocal { public void doSomethingWithObject(Object obj) { // code } } In this case you might want to pass in an instance of your myWidget component, however the interface for myAction won't include myWidget as it is not directly referenced by any of its methods. To get around 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(). 25.7.3. Dates and Times Date values are serialized into a String representation that is accurate to the millisecond. On the client side, use a Javascript Date object to work with date values. On the server side, use any java.util.Date (or descendent, such as java.sql.Date or java.sql.Timestamp class. 25.7.4. Enums On the client side, enums are treated the same as Strings. When setting the value for an enum parameter, simply use the String representation of the enum. Take the following component as an example: @Name("paintAction") public class paintAction implements paintLocal { public enum Color {red, green, blue, yellow, orange, purple}; public void paint(Color color) { // code } } To call the paint() method with the color red, pass the parameter value as a String literal: Seam.Component.getInstance("paintAction").paint("red"); The inverse is also true - that is, if a component method returns an enum parameter (or contains an enum field anywhere in the returned object graph) then on the client-side it will be represented as a String. 25.7.5. Collections 25.7.5.1. Bags Bags cover all collection types including arrays, collections, lists, sets, (but excluding Maps - see the next section for those), and are implemented client-side as a Javascript array. When calling a component method that accepts one of these types as a parameter, your parameter should be a Javascript array. If a component method returns one of these types, then the return value will also be a Javascript array. The remoting framework is clever enough on the server side to convert the bag to an appropriate type for the component method call. 25.7.5.2. Maps As there is no native support for Maps within Javascript, a simple Map implementation is provided with the 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: var map = new Seam.Remoting.Map(); 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 of these methods are equivalent to their Java counterpart. Where the method returns a collection, such as keySet() and values(), a Javascript Array object will be returned that contains the key or value objects (respectively). 25.8. Debugging To aid in tracking down bugs, it is possible to enable a debug mode which will display the contents of all the packets send back and forth between the client and server in a popup window. To enable debug mode, either execute the setDebug() method in Javascript: Seam.Remoting.setDebug(true); Or configure it via components.xml: To turn off debugging, call setDebug(false). If you want to write your own messages to the debug log, call Seam.Remoting.log(message). 25.9. Handling Exceptions When invoking a remote component method, it is possible to specify an exception handler which will process the response in the event of an exception during component invocation. To specify an exception handler function, include a reference to it after the callback parameter in your JavaScript: var callback = function(result) { alert(result); }; var exceptionHandler = function(ex) { alert("An exception occurred: " + ex.getMessage()); }; Seam.Component.getInstance("helloAction").sayHello(name, callback, exceptionHandler); If you do not have a callback handler defined, you must specify null in its place: var exceptionHandler = function(ex) { alert("An exception occurred: " + ex.getMessage()); }; Seam.Component.getInstance("helloAction").sayHello(name, null, exceptionHandler); The exception object that is passed to the exception handler exposes one method, getMessage() that returns the exception message which is produced by the exception thrown by the @WebRemote method. 25.10. The Loading Message The default loading message that appears in the top right corner of the screen can be modified, its rendering customised or even turned off completely. 25.10.1. Changing the message To change the message from the default "Please Wait..." to something different, set the value of Seam.Remoting.loadingMessage: Seam.Remoting.loadingMessage = "Loading..."; 25.10.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: // don't display the loading indicator Seam.Remoting.displayLoadingMessage = function() {}; Seam.Remoting.hideLoadingMessage = function() {}; 25.10.3. A Custom Loading Indicator It is also possible to override the loading indicator to display an animated icon, or anything else that you want. To do this override the displayLoadingMessage() and hideLoadingMessage() messages with your own implementation: Seam.Remoting.displayLoadingMessage = function() { // Write code here to display the indicator }; Seam.Remoting.hideLoadingMessage = function() { // Write code here to hide the indicator }; 25.11. Controlling what data is returned When a remote method is executed, the result is serialized into an XML response that is returned to the client. This response is then unmarshaled by the client into a Javascript object. For complex types (i.e. Javabeans) that include references to other objects, all of these referenced objects are also serialized as part of the response. These objects may reference other objects, which may reference other objects, and so forth. If left unchecked, this object "graph" could potentially be enormous, depending on what relationships exist between your objects. And as a side issue (besides the potential verbosity of the response), you might also wish to prevent sensitive information from being exposed to the client. Seam Remoting provides a simple means to "constrain" the object graph, by specifying the exclude field of the remote method's @WebRemote annotation. This field accepts a String array containing one or more paths specified using dot notation. When invoking a remote method, the objects in the result's object graph that match these paths are excluded from the serialized result packet. For all our examples, we'll use the following Widget class: @Name("widget") public class Widget { private String value; private String secret; private Widget child; private Map widgetMap; private List widgetList; // getters and setters for all fields } 25.11.1. Constraining normal fields If your remote method returns an instance of Widget, but you don't want to expose the secret field because it contains sensitive information, you would constrain it like this: @WebRemote(exclude = {"secret"}) public Widget getWidget(); The value "secret" refers to the secret field of the returned object. Now, suppose that we don't care about exposing this particular field to the client. Instead, notice that the Widget value that is returned has 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: @WebRemote(exclude = {"child.secret"}) public Widget getWidget(); 25.11.2. Constraining Maps and Collections The other place that objects can exist within an object graph are within a Map or some kind of collection (List, Set, Array, etc). Collections are easy, and are treated like any other field. For example, 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: @WebRemote(exclude = {"widgetList.secret"}) public Widget getWidget(); To constrain a Map's key or value, the notation is slightly different. Appending [key] after the Map's field name will constrain the Map's key object values, while [value] will constrain the value object values. The following example demonstrates how the values of the widgetMap field have their secret field constrained: @WebRemote(exclude = {"widgetMap[value].secret"}) public Widget getWidget(); 25.11.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 in the result's object graph it appears. This notation uses either the name of the component (if the object is a Seam component) or the fully qualified class name (only if the object is not a Seam component) and is expressed using square brackets: @WebRemote(exclude = {"[widget].secret"}) public Widget getWidget(); 25.11.4. Combining Constraints Constraints can also be combined, to filter objects from multiple paths within the object graph: @WebRemote(exclude = {"widgetList.secret", "widgetMap[value].secret"}) public Widget getWidget(); 25.12. JMS Messaging Seam Remoting provides experimental support for JMS Messaging. This section describes the JMS support that is currently implemented, but please note that this may change in the future. It is currently not recommended that this feature is used within a production environment. 25.12.1. Configuration Before you can subscribe to a JMS topic, you must first configure a list of the topics that can be subscribed to by Seam Remoting. List the topics under org.jboss.seam.remoting.messaging.subscriptionRegistry.allowedTopics in seam.properties, web.xml or components.xml. 25.12.2. Subscribing to a JMS Topic The following example demonstrates how to subscribe to a JMS Topic: function subscriptionCallback(message) { if (message instanceof Seam.Remoting.TextMessage) alert("Received message: " + message.getText()); } Seam.Remoting.subscribe("topicName", subscriptionCallback); The Seam.Remoting.subscribe() method accepts two parameters, the first being the name of the JMS Topic to subscribe to, the second being the callback function to invoke when a message is received. There are two types of messages supported, Text messages and Object messages. If you need to test for the type of message that is passed to your callback function you can use the instanceof operator to test whether the message is a Seam.Remoting.TextMessage or Seam.Remoting.ObjectMessage. A TextMessage contains the text value in its text field (or alternatively call getText() on it), while an ObjectMessage contains its object value in its value field (or call its getValue() method). 25.12.3. Unsubscribing from a Topic To unsubscribe from a topic, call Seam.Remoting.unsubscribe() and pass in the topic name: Seam.Remoting.unsubscribe("topicName"); 25.12.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 new messages. 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. It controls how long a request to the server should wait for a new message before timing out and sending an empty response. Its default is 0 seconds, which means that when the server is polled, if there are no messages 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 a message means that a server thread is tied up until a message is received, or until the request times out. If many such requests are being served simultaneously, it could mean a large number of threads become tied up because of this reason. It is recommended that you set these options via components.xml, however they can be overridden via Javascript if desired. The following example demonstrates how to configure the polling to occur much more aggressively. You should set these parameters to suitable values for your application: Via components.xml: Via JavaScript: // 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 messages Seam.Remoting.pollTimeout = 5; Chapter 26. Seam and the Google Web Toolkit 26.1. Configuration 26.2. Preparing your component 26.3. Hooking up a GWT widget to the Seam component 26.4. GWT Ant Targets For those that prefer to use the Google Web Toolkit (GWT) to develop dynamic AJAX applications, Seam provides an integration layer that allows GWT widgets to interact directly with Seam components. To use GWT, we assume that you are already familiar with the GWT tools - more information can be found at http://code.google.com/webtoolkit/. This chapter does not attempt to explain how GWT works or how to use it. 26.1. Configuration There is no special configuration required to use GWT in a Seam application, however the Seam resource servlet must be installed. See Chapter 29, Configuring Seam and packaging Seam applications for details. 26.2. Preparing your component The first step in preparing a Seam component to be called via GWT, is to create both synchronous and asynchronous service interfaces for the methods you wish to call. Both of these interfaces should extend the GWT interface com.google.gwt.user.client.rpc.RemoteService: public interface MyService extends RemoteService { public String askIt(String question); } The asynchronous interface should be identical, except that it also contains an additional AsyncCallback parameter for each of the methods it declares: public interface MyServiceAsync extends RemoteService { public void askIt(String question, AsyncCallback callback); } The asynchronous interface, in this example MyServiceAsync, will be implemented by GWT and should never be implemented directly. The next step, is to create a Seam component that implements the synchronous interface: @Name("org.jboss.seam.example.remoting.gwt.client.MyService") public class ServiceImpl implements MyService { @WebRemote public String askIt(String question) { if (!validate(question)) { throw new IllegalStateException("Hey, this shouldn't happen, I checked on the client, " + "but its always good to double check."); } return "42. Its the real question that you seek now."; } public boolean validate(String q) { ValidationUtility util = new ValidationUtility(); return util.isValid(q); } } The name of the seam component must match the fully qualified name of the GWT client interface (as shown), or the seam resource servlet will not be able to find it when a client makes a GWT call. The methods that are to be made accessible via GWT also need to be annotated with the @WebRemote annotation. 26.3. Hooking up a GWT widget to the Seam component The next step, is to write a method that returns the asynchronous interface to the component. This method can be located inside the widget class, and will be used by the widget to obtain a reference to the asynchronous client stub: private MyServiceAsync getService() { String endpointURL = GWT.getModuleBaseURL() + "seam/resource/gwt"; MyServiceAsync svc = (MyServiceAsync) GWT.create(MyService.class); ((ServiceDefTarget) svc).setServiceEntryPoint(endpointURL); return svc; } The final step is to write the widget code that invokes the method on the client stub. The following example creates a simple user interface with a label, text input and a button: public class AskQuestionWidget extends Composite { private AbsolutePanel panel = new AbsolutePanel(); public AskQuestionWidget() { Label lbl = new Label("OK, what do you want to know?"); panel.add(lbl); final TextBox box = new TextBox(); box.setText("What is the meaning of life?"); panel.add(box); Button ok = new Button("Ask"); ok.addClickListener(new ClickListener() { public void onClick(Widget w) { ValidationUtility valid = new ValidationUtility(); if (!valid.isValid(box.getText())) { Window.alert("A question has to end with a '?'"); } else { askServer(box.getText()); } } }); panel.add(ok); initWidget(panel); } private void askServer(String text) { getService().askIt(text, new AsyncCallback() { public void onFailure(Throwable t) { Window.alert(t.getMessage()); } public void onSuccess(Object data) { Window.alert((String) data); } }); } ... When clicked, the button invokes the askServer() method passing the contents of the input text (in this example, validation is also performed to ensure that the input is a valid question). The askServer() method acquires a reference to the asynchronous client stub (returned by the getService() method) and invokes the askIt() method. The result (or error message if the call fails) is shown in an alert window. [Image] The complete code for this example can be found in the Seam distribution in the examples/remoting/gwt directory. 26.4. GWT Ant Targets For deployment of GWT apps, there is a compile-to-Javascript step (which compacts and obfuscates the code). There is an ant utility which can be used instead of the command line or GUI utility that GWT provides. To use this, you will need to have the ant task jar in your ant classpath, as well as GWT downloaded (which you will need for hosted mode anyway). Then, in your ant file, place (near the top of your ant file): Create a build.properties file, which has the contents: gwt.home=/gwt_home_dir This of course should point to the directory where GWT is installed. Then to use it, create a target: This target when called will compile the GWT application, and copy it to the specified directory (which would be in the webapp part of your war - remember GWT generates HTML and Javascript artifacts). You never edit the resulting code that gwt-compile generates - you always edit in the GWT source directory. Remember that GWT comes with a hosted mode browser - you should be using that if you are developing with GWT. If you aren't using that, and are just compiling it each time, you aren't getting the most out of the toolkit (in fact, if you can't or won't use the hosted mode browser, I would go far as to say you should NOT be using GWT at all - it's that valuable!). Chapter 27. Spring Framework integration 27.1. Injecting Seam components into Spring beans 27.2. Injecting Spring beans into Seam components 27.3. Making a Spring bean into a Seam component 27.4. Seam-scoped Spring beans 27.5. Using Spring PlatformTransactionManagement 27.6. Using a Seam Managed Persistence Context in Spring 27.7. Using a Seam Managed Hibernate Session in Spring 27.8. Spring Application Context as a Seam Component 27.9. Using a Spring TaskExecutor for @Asynchronous The Spring integration module allows easy migration of Spring-based projects to Seam and allows Spring applications to take advantage of key Seam features like conversations and Seam's more sophisticated persistence context management. Note! The Spring integration code is included in the jboss-seam-ioc library. This dependency is required for all seam-spring integration techniques covered in this chapter. 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 and OpenSessionInViewFilter * Support for Spring TaskExecutors to back @Asynchronous calls 27.1. Injecting Seam components into Spring beans Injecting Seam component instances into Spring beans is accomplished using the namespace handler. To enable the Seam namespace handler, the Seam namespace must be added to the Spring beans definition file: Now any Seam component may be injected into any Spring bean: 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 Spring bean id. Now for the caveat! Seam was designed from the ground up to support a stateful component model with multiple contexts. Spring was not. Unlike Seam bijection, Spring injection does not occur at method invocation time. Instead, injection happens only when the Spring bean is instantiated. So the instance available when the bean is instantiated will be the same instance that the bean uses for the entire life of the bean. For example, if a 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 call this problem scope impedance. Seam bijection ensures that scope impedance is maintained naturally as an 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 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 a more robust way to use Seam-managed persistence contexts as a replacement for the Spring OpenEntityManagerInView filter see section on Using a Seam Managed Persistence Context in Spring) 27.2. Injecting Spring beans into Seam components It is even easier to inject Spring beans into Seam component instances. Actually, there are two possible approaches: * inject a Spring bean using an EL expression * make the Spring bean a Seam component We'll discuss the second option in the next section. The easiest approach is to access the Spring beans via EL. The Spring DelegatingVariableResolver is an integration point Spring provides for integrating Spring with JSF. This VariableResolver makes all Spring beans available in EL by their bean id. You'll need to add the DelegatingVariableResolver to faces-config.xml: org.springframework.web.jsf.DelegatingVariableResolver Then you can inject Spring beans using @In: @In("#{bookingService}") private BookingService bookingService; The use of Spring beans in EL is not limited to injection. Spring beans may be used anywhere that EL expressions are used in Seam: process and pageflow definitions, working memory assertions, etc... 27.3. Making a Spring bean into a Seam component The namespace handler can be used to make any Spring bean a Seam component. Just place the tag within the declaration of the bean that you wish to be a Seam component: By default, will create a STATELESS Seam component with class and name provided in the bean definition. Occasionally, such as when a FactoryBean is used, the class of the Spring bean may not be the class appearing in the bean definition. In such cases the class should be explicitly specified. A Seam component name may be explicitly specified in cases where there is potential for a naming conflict. The scope attribute of may be used if you wish the Spring bean to be managed in a particular Seam scope. The Spring bean must be scoped to prototype if the Seam scope specified is anything other than STATELESS. Pre-existing Spring beans usually have a fundamentally stateless character, so this attribute is not usually needed. 27.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 that Spring's component model was never architected to support statefulness, so please use this feature with great care. In particular, clustering of session or conversation scoped Spring beans is deeply problematic, and care must be taken when injecting a bean or component from a wider scope into a bean of a narrower scope. By specifying once in a Spring bean factory configuration, all of the Seam scopes will be available to Spring beans as custom scopes. To associate a Spring bean with a particular 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 when referenced 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 auto created. Seam-scoped Spring beans defined this way can be injected into other Spring beans without the use of . However, care must be taken to ensure scope impedance is maintained. The normal approach used in Spring is to specify in the bean definition. However, Seam-scoped Spring beans are not compatible with . So if you need to inject a Seam-scoped Spring bean into a singleton, must be used: ... 27.5. Using Spring PlatformTransactionManagement Spring provides an extensible transaction management abstraction with support for many transaction APIs (JPA, Hibernate, JDO, and JTA) Spring also provides tight integrations with many application server TransactionManagers such as Websphere and Weblogic. Spring transaction management exposes support for many advanced features such as nested transactions and supports full Java EE transaction propagation rules like REQUIRES_NEW and NOT_SUPPORTED. For more information see the 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 synchronization capabilities for synchronization callbacks. 27.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 an EntityManager open for the life of a conversation. This eliminates many of the problems associated with 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 context beyond the scope of a single web request (OpenEntityManagerInViewFilter). So, it would be nice if Spring developers could have access to a Seam managed persistence context using all of the same tools Spring provides for integration with JPA(e.g. PersistenceAnnotationBeanPostProcessor, JpaTemplate, etc.) Seam provides a way for Spring to access a Seam managed persistence context with Spring's provided JPA 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 (e.g. asynchronous quartz job) * allows for using Seam managed persistence contexts with Spring managed transactions (will need to flush the persistence context manually) Spring's persistence context propagation model allows only one open EntityManager per EntityManagerFactory so the Seam integration works by wrapping an EntityManagerFactory around a Seam managed persistence context. Where 'persistenceContextName' is the name of the Seam managed persistence context component. By default this EntityManagerFactory has a unitName equal to the Seam component name or in this case 'entityManager'. If you wish to provide a different unitName you can do so by providing a persistenceUnitName like so: This EntityManagerFactory can then be used in any Spring provided tools. For example, using Spring's PersistenceAnnotationBeanPostProcessor is the exact same as before. If you define your real EntityManagerFactory in Spring but wish to use a Seam managed persistence context you can tell the PersistenceAnnotationBeanPostProcessor which persistenctUnitName you wish to use by default by specifying the 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 persistence context as they would be fore a Seam managed persistence context. 27.7. Using a Seam Managed Hibernate Session in Spring The Seam Spring integration also provides support for complete access to a Seam managed Hibernate session using spring's tools. This integration is very similar to the JPA integration. Like Spring's JPA integration spring's propagation model allows only one open EntityManager per EntityManagerFactory per transaction??? to be available to spring tools. So, the Seam Session integration works 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 provides support for calls to SessionFactory.getCurrentInstance() as long as you call getCurrentInstance() on the SeamManagedSessionFactory. 27.8. Spring Application Context as a Seam Component Although it is possible to use the Spring ContextLoaderListener to start your application's Spring ApplicationContext 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 a Spring ApplicationContext. To use this Seam component place the 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 element following standard components.xml multi value practices. 27.9. Using a Spring TaskExecutor for @Asynchronous Spring provides an abstraction for executing code asynchronously called a TaskExecutor. The Spring Seam 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 fallback Seam Dispatcher can be provided to handle scheduled asynchronous event like so: Chapter 28. Hibernate Search 28.1. Introduction 28.2. Configuration 28.3. Usage 28.1. Introduction Full text search engines like Apache Lucene™ are a very powerful technology that bring full text and efficient 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 / index synchronization and returns regular managed objects that are matched by full text queries. Keep in mind, thought, that there are mismatches that arise when dealing with an object domain model over a text 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 and Hibernate. As a natural extension, JBoss Seam provides an Hibernate Search integration. Please refer to the Hibernate Search documentation for information specific to the Hibernate Search project. 28.2. Configuration Hibernate Search is configured either in the META-INF/persistence.xml or hibernate.cfg.xml file. Hibernate Search configuration has sensible defaults for most configuration parameters. Here is a minimal persistence unit configuration to get started. java:/DefaultDS [...] If you plan to target Hibernate Annotations or EntityManager 3.2.x (embedded into JBoss AS 4.2.GA), you also need to configure the appropriate event listeners. java:/DefaultDS [...] Note This step is no longer necessary if Hibernate Annotation or EntityManager 3.3.x are used. 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, don't forget to update application.xml 28.3. Usage Hibernate Search uses annotations to map entities to a Lucene index, check the reference documentation for more informations. Hibernate Search is fully integrated with the API and semantic of JPA / Hibernate. Switching from a HQL or Criteria based query requires just a few lines of code. The main API the application interacts with is the FullTextSession API (subclass of Hibernate's Session). When Hibernate Search is present, JBoss Seam injects a FullTextSession. @Stateful @Name("search") public class FullTextSearchAction implements FullTextSearch, Serializable { @In FullTextSession session; public void search(String searchString) { org.apache.lucene.search.Query luceneQuery = getLuceneQuery(); org.hibernate.Query query session.createFullTextQuery(luceneQuery, Product.class); searchResults = query .setMaxResults(pageSize + 1) .setFirstResult(pageSize * currentPage) .list(); } [...] } Note FullTextSession extends org.hibernate.Session so that it can be used as a regular Hibernate Session If the Java Persistence API is used, a smoother integration is proposed. @Stateful @Name("search") public class FullTextSearchAction implements FullTextSearch, Serializable { @In FullTextEntityManager em; public void search(String searchString) { org.apache.lucene.search.Query luceneQuery = getLuceneQuery(); javax.persistence.Query query = em.createFullTextQuery(luceneQuery, Product.class); searchResults = query .setMaxResults(pageSize + 1) .setFirstResult(pageSize * currentPage) .getResultList(); } [...] } 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 (i.e. via the @PersistenceContext annotation), it is not possible to replace the EntityManager interface by the FullTextEntityManager interface in the declaration statement. However, the implementation injected will be a FullTextEntityManager implementation: downcasting is then possible. @Stateful @Name("search") public class FullTextSearchAction implements FullTextSearch, Serializable { @PersistenceContext EntityManager em; public void search(String searchString) { org.apache.lucene.search.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(); } [...] } Caution 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 of Hibernate Search. Chapter 29. Configuring Seam and packaging Seam applications 29.1. Basic Seam configuration 29.1.1. Integrating Seam with JSF and your servlet container 29.1.2. Using Facelets 29.1.3. Seam Resource Servlet 29.1.4. Seam servlet filters 29.1.5. Integrating Seam with your EJB container 29.1.6. Don't forget! 29.2. Using Alternate JPA Providers 29.3. Configuring Seam in Java EE 5 29.3.1. Packaging 29.4. Configuring Seam in J2EE 29.4.1. Boostrapping Hibernate in Seam 29.4.2. Boostrapping JPA in Seam 29.4.3. Packaging 29.5. Configuring Seam in Java SE, without JBoss Embedded 29.6. Configuring Seam in Java SE, with JBoss Embedded 29.6.1. Installing Embedded JBoss 29.6.2. Packaging 29.7. Configuring jBPM in Seam 29.7.1. Packaging 29.8. Configuring SFSB and Session Timeouts in JBoss AS 29.9. Running Seam in a Portlet 29.10. Deploying custom resources Configuration is a very boring topic and an extremely tedious pastime. Unfortunately, several lines of XML are required to integrate Seam into your JSF implementation and servlet container. There's no need to be too put off by the following sections; you'll never need to type any of this stuff yourself, since you can just use seam-gen to start your application or you can copy and paste from the example applications! 29.1. Basic Seam configuration First, let's look at the basic configuration that is needed whenever we use Seam with JSF. 29.1.1. Integrating Seam with JSF and your servlet container Of course, you need a faces servlet! Faces Servlet javax.faces.webapp.FacesServlet 1 Faces Servlet *.seam (You can adjust the URL pattern to suit your taste.) In addition, Seam requires the following entry in your web.xml file: org.jboss.seam.servlet.SeamListener This listener is responsible for bootstrapping Seam, and for destroying session and application contexts. Some JSF implementations have a broken implementation of server-side state saving that interferes with Seam's conversation propagation. If you have problems with conversation propagation during form submissions, try switching to client-side state saving. You'll need this in web.xml: javax.faces.STATE_SAVING_METHOD client There is a minor gray area in the JSF specification regarding the mutability of view state values. Since Seam uses the JSF view state to back its PAGE scope this can become an issue in some cases. If you're using server side state saving with the JSF-RI and you want a PAGE scoped bean to keep its exact value for a given view of a page you will need to specify the following context-param. Otherwise if a user uses the "back" button a PAGE scoped component will have the latest value if it has changed not the value of the "back" page. (see Spec Issue ). This setting is not enabled by default because of the performance hit of serializing the JSF view with every request. com.sun.faces.serializeServerState true 29.1.2. Using Facelets If you want follow our advice and use Facelets instead of JSP, add the following lines to faces-config.xml: com.sun.facelets.FaceletViewHandler И следующие строки в web.xml: javax.faces.DEFAULT_SUFFIX .xhtml If you are using facelets in JBoss AS, you'll find that Facelets logging is broken (the log messages don't make it to the server log). Seam provides a bridge to fix this, to use it copy lib/interop/jboss-seam-jul.jar to $JBOSS_HOME/server/default/deploy/jboss-web.deployer/jsf-libs/ and include the jboss-seam-ui.jar in the WEB-INF/lib of your application. The Facelets logging catagories are itemized in the Facelets Developer Documentation. 29.1.3. Seam Resource Servlet The Seam Resource Servlet provides resources used by Seam Remoting, captchas (see the security chapter) and some JSF UI controls. Configuring the Seam Resource Servlet requires the following entry in web.xml: Seam Resource Servlet org.jboss.seam.servlet.SeamResourceServlet Seam Resource Servlet /seam/resource/* 29.1.4. Seam servlet filters Seam doesn't need any servlet filters for basic operation. However, there are several features which depend upon the use of filters. To make things easier, Seam lets you add and configure servlet filters just like you would configure other built-in Seam components. To take advantage of this feature, we must first install a master filter in web.xml: Seam Filter org.jboss.seam.servlet.SeamFilter Seam Filter /* 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 in addition 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. * disabled — Used to disable a built in filter. Note that the patterns are matched against the URI path of the request (see HttpServletRequest.getURIPath()) and that the name of the servlet context is removed before matching. Adding the master filter enables the following built-in filters. 29.1.4.1. Exception handling This filter provides the exception mapping functionality in pages.xml (almost all applications will need this). It also takes care of rolling back uncommitted transactions when uncaught exceptions occur. (According to the Java EE specification, the web container should do this automatically, but we've found that this behavior cannot be relied upon in all application servers. And it is certainly not required of plain servlet engines like Tomcat.) By default, the exception handling filter will process all requests, however this behavior may be adjusted by adding a entry to components.xml, as shown in this example: 29.1.4.2. Conversation propagation with redirects This filter allows Seam to propagate the conversation context across browser redirects. It intercepts any 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: 29.1.4.3. URL rewriting This filter allows Seam to apply URL rewriting for views based on configuration in the pages.xml file. This filter is not activate by default, but can be activated by adding the configuration to components.xml: The view-mapping parameter must match the servlet mapping defined for the Faces Servlet in the web.xml file. If ommitted, the rewrite filter assumes the pattern *.seam. 29.1.4.4. Multipart form submissions This feature is necessary when using the Seam file upload JSF control. It detects multipart form requests and processes them according to the multipart/form-data specification (RFC-2388). To override 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 of held 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. The default setting is 0 (no size limit). 29.1.4.5. 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 is specified by encoding no matter whether the request already specifies an encoding or not. If set to false, the request encoding will only be set if the request doesn't already specify an encoding. The default setting is false. 29.1.4.6. RichFaces If RichFaces is used in your project, Seam will install the RichFaces Ajax filter for you, making sure to install it before all other built-in filters. You don't need to install the RichFaces Ajax filter in web.xml yourself. 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 the same 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. * 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 browser from caching the resource. * log4j-init-file — is used to setup per-application logging. A path, relative to web application context, to the log4j.xml configuration file should be provided. 29.1.4.7. Identity Logging This filter adds the authenticated user name to the log4j mapped diagnostic context so that it can be included 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 adding a entry to components.xml, as shown in this example: 29.1.4.8. Context management for custom servlets Requests sent direct to some servlet other than the JSF servlet are not processed through the JSF lifecycle, so Seam provides a servlet filter that can be applied to any other servlet that needs access to Seam components. This filter allows custom servlets to interact with the Seam contexts. It sets up the Seam contexts at the beginning of each request, and tears them down at the end of the request. You should make sure that this filter is never applied to the JSF FacesServlet. Seam uses the phase listener for context management 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 request parameter 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. Seam exposes the conversation id as a property of the built in component conversation. 29.1.4.9. Adding custom filters Seam can install your filters for you, allowing you to specify where in the chain your filter is placed (the servlet specification doesn't provide a well defined order if you specify your filters in a web.xml). Just add the @Filter annotation to your Seam component (which must implement javax.servlet.Filter): @Startup @Scope(APPLICATION) @Name("org.jboss.seam.web.multipartFilter") @BypassInterceptors @Filter(within="org.jboss.seam.web.ajax4jsfFilter public class MultipartFilter extends AbstractFilter { Adding the @Startup annotation means thar the component is available during Seam startup; bijection isn't available here (@BypassInterceptors); and the filter should be further down the chain than the RichFaces filter (@Filter(within="org.jboss.seam.web.ajax4jsfFilter")). 29.1.5. Integrating Seam with your EJB container In a Seam application, EJB components have a certain duality, as they are managed by both the EJB container and Seam. Actually, it's more that Seam resolves EJB component references, manages the lifetime of stateful session bean components, and also participates in each method call via interceptors. Let's start with the configuration of the Seam interceptor chain. We need to apply the SeamInterceptor to our Seam EJB components. This interceptor delegates to a set of built-in server-side interceptors that handle such concerns as bijection, conversation demarcation, and business process signals. The simplest way to do this across an entire application is to add the following interceptor configuration in ejb-jar.xml: org.jboss.seam.ejb.SeamInterceptor * org.jboss.seam.ejb.SeamInterceptor 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. A better approach is to specify a pattern that Seam can use to calculate the JNDI name from the EJB name. Unfortunately, there is no standard mapping to global JNDI defined in the EJB3 specification, so this mapping is vendor-specific (and may depend on your own naming conventions as well). We usually specify this option in components.xml. For JBoss AS, the following pattern is correct: In this case, earName is the name of the EAR in which the bean is deployed, Seam replaces #{ejbName} with the name of the EJB, and the final segment represents the type of interface (local or remote). Outside the context of an EAR (when using the JBoss Embeddable EJB3 container), the first segment is dropped since there is no EAR, leaving us with the following pattern: How these JNDI names are resolved and somehow locate an EJB component might appear a bit like black magic at this point, so let's dig into the details. First, let's talk about how the EJB components get into JNDI. The folks at JBoss don't care much for XML, if you can't tell. So when they designed JBoss AS, they decided that EJB components would get assigned a global JNDI name automatically, using the pattern just described (i.e., EAR name/EJB name/interface type). The EJB name is the first non-empty value from the following list: * The value of the element in ejb-jar.xml * The value of the name attribute in the @Stateless or @Stateful annotation * The simple name of the bean class Let's look at an example. Assume that you have the following EJB bean and interface defined. package com.example.myapp; import javax.ejb.Local; @Local public class Authenticator { boolean authenticate(); } package com.example.myapp; import javax.ejb.Stateless; @Stateless @Name("authenticator") public class AuthenticatorBean implements Authenticator { public boolean authenticate() { ... } } Assuming your EJB bean class is deployed in an EAR named myapp, the global JNDI name myapp/AuthenticatorBean/local will be assigned to it on JBoss AS. As you learned, you can reference this EJB component as a Seam component with the name authenticator and Seam will take care of finding it in JNDI according to the JNDI pattern (or @JndiName annotation). So what about the rest of the application servers? Well, according to the Java EE spec, which most vendors try to adhere to religiously, you have to declare an EJB reference for your EJB in order for it to be assigned a JNDI name. That requires some XML. It also means that it is up to you to establish a JNDI naming convention so that you can leverage the Seam JNDI pattern. You might find the JBoss convention a good one to follow. There are two places you have to define the EJB reference when using Seam on non-JBoss application servers. If you are going to be looking up the Seam EJB component through JSF (in a JSF view or as a JSF action listener) or a Seam JavaBean component, then you must declare the EJB reference in web.xml. Here is the EJB reference for the example component just shown: myapp/AuthenticatorBean/local Session org.example.vehicles.action.Authenticator This reference will cover most uses of the component in a Seam application. However, if you want to be able to inject a Seam EJB component into another Seam EJB component using @In, you need to define this EJB reference in another location. This time, it must be defined in ejb-jar.xml, and it's a bit tricker. Within the context of an EJB method call, you have to deal with a somewhat sheltered JNDI context. When Seam attempts to find another Seam EJB component to satisfy an injection point defined using @In, it isn't going to be successful looking up the component in JNDI. You cannot simply resolve JNDI names as you please. You have to define those references explicitly. Unlike with the web context, however, you cannot declare EJB references globally for all EJB components. Instead, you have to specify the JNDI resources for a given EJB component one-by-one (this applies to JBoss AS 5 in addition to non-JBoss application servers). Let's assume that we have an EJB named RegisterAction (the name is resolved using the three steps mentioned previously). That EJB has the following Seam injection: @In(create = true) Authenticator authenticator; In order for this injection to work, the link must be established in the ejb-jar.xml file as follows: RegisterAction myapp/AuthenticatorAction/local Session com.example.myapp.Authenticator ... Notice that the contents of the are identical to what we defined in web.xml. What we are doing is bringing the reference into the EJB context where it can be used by the RegisterAction bean. You will need to add one of these references for any injection of a Seam EJB compoenent into another Seam EJB component using @In. (You can see an example of this setup in the jee5/booking example). But what about @EJB? It's true that you can inject one EJB into another using @EJB. However, by doing so, you are injecting the actual EJB reference rather than the Seam EJB component instance. In this case, some Seam features will work, while others won't. That's because Seam's interceptor is invoked on any method call to an EJB component. But that only invokes Seam's server-side interceptor chain. What you lose is Seam's state management and Seam's client-side interceptor chain. Client-side interceptors handle concerns such as security and concurrency. Also, when injecting a SFSB, there is no guarantee that you will get the SFSB bound to the active session or conversation, whatever the case may be. Thus, you definitely want to inject the Seam EJB component using @In. That covers how JNDI names are defined and used. The lesson is that with some application servers, such as GlassFish, you are going to have to specify JNDI names for all EJB components explicitly, and sometimes twice! And even if you are following the same naming convention as JBoss AS, the JNDI pattern in Seam may need to be altered. For instance, the global JNDI names are automatically prefixed with java:comp/env on GlassFish, so you need to define the JNDI pattern as follows: Finally, let's talk about transactions. In an EJB3 environment, we recommend the use of a special built-in component for transaction management, that is fully aware of container transactions, and can correctly process transaction success events registered with the Events component. If you don't add this line to your components.xml file, Seam won't know when container-managed transactions end: 29.1.6. Don't forget! 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 Seam components are deployed (even an empty properties file will do). At startup, Seam will scan any archives with seam.properties files for seam components. In a web archive (WAR) file, you must place a seam.properties file in the WEB-INF/classes directory if you have any Seam components included here. That's why all the Seam examples have an empty seam.properties file. You can't just delete this file and expect everything to still work! You might think this is silly and what kind of idiot framework designers would make an empty file affect the behavior of their software?? Well, this is a workaround for a limitation of the JVM—if we didn't use this mechanism, our next best option would be to force you to list every component explicitly in components.xml, just like some other competing frameworks do! I think you'll like our way better. 29.2. Using Alternate JPA Providers Seam comes packaged and configured with Hibernate as the default JPA provider. If you require using a different JPA provider you must tell seam about it. This is a workaround Configuration of the JPA provider will be easier in the future and will not require configuration changes, unless you are adding a custom persistence provider implementation. 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 takes precedence 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 you own implementation of the PersistenceProvider. Use HibernatePersistenceProvider as a starting point (don't forget to give back to the community :). 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 ever properties your provider needs. Don't forget to package your new provider's jar files in the application if they are needed. 29.3. Configuring Seam in Java EE 5 [Image] If you're running in a Java EE 5 environment, this is all the configuration required to start using Seam! 29.3.1. Packaging Once you've packaged all this stuff together into an EAR, the archive structure will look something like 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 Register.class RegisterBean.class ... 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 that supports EJB 3.0. I really wish that was all there was to say on the topic of configuration but unfortunately we're only about a third of the way there. If you're too overwhelmed by all this tedious configuration stuff, feel free to skip over the rest of this section and come back to it later. 29.4. Configuring Seam in J2EE Seam is useful even if you're not yet ready to take the plunge into EJB 3.0. In this case you would use Hibernate3 or JPA instead of EJB 3.0 persistence, and plain JavaBeans instead of session beans. You'll miss out on some of the nice features of session beans but it will be very easy to migrate to EJB 3.0 when you're ready and, in the meantime, you'll be able to take advantage of Seam's unique declarative state management architecture. [Image] Seam JavaBean components do not provide declarative transaction demarcation like session beans do. You could manage your transactions manually using the JTA UserTransaction or declaratively using Seam's @Transactional annotation. But most applications will just use Seam managed transactions when using Hibernate with JavaBeans. The Seam distribution includes a version of the booking example application that uses Hibernate3 and JavaBeans instead of EJB3, and another version that uses JPA and JavaBeans. These example applications are ready to deploy into any J2EE application server. 29.4.1. Boostrapping Hibernate in Seam Seam will bootstrap a Hibernate SessionFactory from your hibernate.cfg.xml file if you install a built-in component: You will also need to configure a managed session if you want a Seam managed Hibernate Session to be available via injection. 29.4.2. Boostrapping JPA in Seam Seam will bootstrap a JPA EntityManagerFactory from your persistence.xml file if you install this 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. 29.4.3. Packaging We can package our application as a WAR, in the following structure: 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/ META-INF/ MANIFEST.MF seam.properties hibernate.cfg.xml org/ jboss/ myapplication/ User.class Login.class Register.class ... login.jsp register.jsp ... If we want to deploy Hibernate in a non-EE environment like Tomcat or TestNG, we need to do a little bit more work. 29.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 Seam how to manage transactions, since there will be no JTA available. If you're using JPA, you can tell Seam to use JPA resource-local transactions, ie. EntityTransaction, like so: If you're using Hibernate, you can tell Seam to use the Hibernate transaction API like this: Of course, you'll also need to define a datasource. A better alternative is to use JBoss Embedded to get access to the EE APIs. 29.6. Configuring Seam in Java SE, with JBoss Embedded JBoss Embedded lets you run EJB3 components outside the context of the Java EE 5 application server. This is especially, but not only, useful for testing. The Seam booking example application includes a TestNG integration test suite that runs on JBoss Embedded via SeamTest. [Image] The booking example application may even be deployed to Tomcat. [Image] 29.6.1. Installing Embedded JBoss Embedded JBoss must by installed into Tomcat for Seam applications to run correctly on it. Embedded JBoss runs with JDK 5 or JDK 6 ( see Section 40.1, “JDK Dependencies” for details on using JDK 6). Embedded JBoss can be downloaded here. The process for installing Embedded JBoss into Tomcat 6 is quite simple. First, you should copy the Embedded JBoss JARs and configuration files into Tomcat. * Copy all files and directories under the Embedded JBoss bootstrap and lib directories, except for the jndi.properties file, into the Tomcat lib directory. * Remove the annotations-api.jar file from the Tomcat lib directory. Next, two configuration files need to be updated to add Embedded JBoss-specific functionality. * Add the Embedded JBoss listener EmbeddedJBossBootstrapListener to conf/server.xml. It must appear after all other listeners in the file: * WAR file scanning should be enabled by adding the WebinfScanner listener to conf/context.xml: WEB-INF/web.xml * If you are using Sun JDK 6, you need to set the Java option sun.lang.ClassLoader.allowArraySyntax to true in the JAVA_OPTS environment variable used by the Catalina startup script (catalina.bat on Windows or catalina.sh on Unix). Open the script appropriate for your operating system in a text editor. Add a new line immediately below the comments at the top of the file where you will define the JAVA_OPTS environment variable. On Windows, use the following syntax: set JAVA_OPTS=%JAVA_OPTS% -Dsun.lang.ClassLoader.allowArraySyntax=true On Unix, use this syntax instead: JAVA_OPTS="$JAVA_OPTS -Dsun.lang.ClassLoader.allowArraySyntax=true" For more configuration options, please see the Embedded JBoss Tomcat integration wiki entry. 29.6.2. Packaging The archive structure of a WAR-based deployment on an servlet engine like Tomcat will look something like this: 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 jsf-api.jar jsf-impl.jar ... my-application.jar/ META-INF/ MANIFEST.MF persistence.xml seam.properties org/ jboss/ myapplication/ User.class Login.class LoginBean.class Register.class RegisterBean.class ... login.jsp register.jsp ... Most of the Seam example applications may be deployed to Tomcat by running ant deploy.tomcat. 29.7. Configuring jBPM in Seam Seam's jBPM integration is not installed by default, so you'll need to enable jBPM by installing a built-in component. You'll also need to explicitly list your process and pageflow definitions. In components.xml: createDocument.jpdl.xml editDocument.jpdl.xml approveDocument.jpdl.xml documentLifecycle.jpdl.xml No further special configuration is needed if you only have pageflows. If you do have business process definitions, you need to provide a jBPM configuration, and a Hibernate configuration for jBPM. The Seam DVD Store demo includes example jbpm.cfg.xml and hibernate.cfg.xml files that will work with Seam: The most important thing to notice here is that jBPM transaction control is disabled. Seam or EJB3 should control the JTA transactions. 29.7.1. Packaging There is not yet any well-defined packaging format for jBPM configuration and process/pageflow definition files. In the Seam examples we've decided to simply package all these files into the root of the EAR. In future, we will probably design some other standard packaging format. So the EAR looks something like this: 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 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 29.8. 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 HTTP Sessions, otherwise SFSB's may time out before the user's HTTP session has ended. JBoss Application Server 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: org.jboss.ejb.plugins.LRUStatefulContextCachePolicy 50 1000000 1800 1800 300 600 400 60 1 0.75 The default HTTP session timeout can be modified in server/default/deploy/jbossweb-tomcat55.sar/conf/web.xml for JBoss 4.0.x, or in server/default/deploy/jboss-web.deployer/conf/web.xml for JBoss 4.2.x. The following entry in this file controls the default session timeout for all web applications: 30 To override this value for your own application, simply include this entry in your application's own web.xml. 29.9. Running Seam in a Portlet If you want to run your Seam application in a portlet, take a look at the JBoss Portlet Bridge, an implementation of JSR-301 that supports JSF within a portlet, with extensions for Seam and RichFaces. See http://labs.jboss.com/portletbridge for more. 29.10. Deploying custom resources Seam scans all jars containing /seam.properties, /META-INF/components.xml or /META-INF/seam.properties on startup for resources. For example, all classes annotated with @Name are registered with Seam as Seam components. You may also want Seam to handle custom resources. A common use case is to handle a specific annotation and Seam provides specific support for this. First, tell Seam which annotations to handle in /META-INF/seam-deployment.properties: # A colon-separated list of annotation types to handle org.jboss.seam.deployment.annotationTypes=com.acme.Foo:com.acme.Bar Then, during application startup you can get hold of all classes annotated with @Foo: @Name("fooStartup") @Scope(APPLICATION) @Startup public class FooStartup { @In("#{deploymentStrategy.annotatedClasses['com.acme.Foo']}") private Set> fooClasses; @In("#{hotDeploymentStrategy.annotatedClasses['com.acme.Foo']}") private Set> hotFooClasses; @Create public void create() { for (Class clazz : fooClasses) { handleClass(clazz); } for (Class clazz : hotFooClasses) { handleClass(clazz); } } } You can also handle any resource. For example, you process any files with the extension .foo.xml. To do this, we need to write a custom deployment handler: public class FooDeploymentHandler implements DeploymentHandler { private Set files = new HashSet(); public String getName() { return "fooDeploymentHandler"; } public Set getFiles() { return files; } public void handle(String name, ClassLoader classLoader) { if (name.endsWith(".foo.xml")) { files.add(classLoader.getResourceAsStream(name)); } } } Here we are just building a list of any files with the suffix .foo.xml. Then, we need to register the deployment handler with Seam. In /META-INF/seam-deployment.properties: # For standard deployment org.jboss.seam.deployment.deploymentHandlers=com.acme.FooDeploymentHandler # For hot deployment org.jboss.seam.deployment.hotDeploymentHandlers=com.acme.FooDeploymentHandler You can register multiple deployment handler using a comma separated list. Seam uses deployment handlers internally to install components and namespaces, therefore the handle() is called too early in inside Seam bootstrap to normally be useful. However, you can easily access the deployment handler during an APPLICATION scoped component's startup: @Name("fooStartup") @Scope(APPLICATION) @Startup public class FooStartup { @In("#{deploymentStrategy['fooDeploymentHandler']}") private MyDeploymentHandler myDeploymentHandler; @In("#{hotDeploymentStrategy['fooDeploymentHandler']}") private MyDeploymentHandler myHotDeploymentHandler; @Create public void create() { for (InputStream is : myDeploymentHandler.getFiles()) { handleFooXml(is); } for (InputStream is : myHotDeploymentHandler.getFiles()) { handleFooXml(is); } } } Chapter 30. Seam annotations 30.1. Annotations for component definition 30.2. Annotations for bijection 30.3. Annotations for component lifecycle methods 30.4. Annotations for context demarcation 30.5. Annotations for use with Seam JavaBean components in a J2EE environment 30.6. Annotations for exceptions 30.7. Annotations for Seam Remoting 30.8. Annotations for Seam interceptors 30.9. Annotations for asynchronicity 30.10. Annotations for use with JSF 30.10.1. Annotations for use with dataTable 30.11. Meta-annotations for databinding 30.12. Annotations for packaging 30.13. Annotations for integrating with the servlet container When you write a Seam application, you'll use a lot of annotations. Seam lets you use annotations to achieve a declarative style of programming. Most of the annotations you'll use are defined by the EJB 3.0 specification. The annotations for data validation are defined by the Hibernate Validator package. Finally, Seam defines its own set of annotations, which we'll describe in this chapter. All of these annotations are defined in the package org.jboss.seam.annotations. 30.1. Annotations for component definition The first group of annotations lets you define a Seam component. These annotations appear on the component class. @Name @Name("componentName") Defines the Seam component name for a class. This annotation is required for all Seam components. @Scope @Scope(ScopeType.CONVERSATION) Defines the default context of the component. The possible values are defined by the ScopeType enumeration: EVENT, PAGE, CONVERSATION, SESSION, BUSINESS_PROCESS, APPLICATION, STATELESS. When no scope is explicitly specified, the default depends upon the component type. For stateless session beans, the default is STATELESS. For entity beans and stateful session beans, the default is CONVERSATION. For JavaBeans, the default is EVENT. @Role @Role(name="roleName", scope=ScopeType.SESSION) Allows a Seam component to be bound to multiple contexts variables. The @Name/@Scope annotations 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 default depends upon the component type, as above. @Roles @Roles({ @Role(name="user", scope=ScopeType.CONVERSATION), @Role(name="currentUser", scope=ScopeType.SESSION) }) Allows specification of multiple additional roles. @BypassInterceptors @BypassInterceptors Disables Seam all interceptors on a particular component or method of a component. @JndiName @JndiName("my/jndi/name") Specifies the JNDI name that Seam will use to look up the EJB component. If no JNDI name is explicitly specified, Seam will use the JNDI pattern specified by org.jboss.seam.core.init.jndiPattern. @Conversational @Conversational Specifies that a conversation scope component is conversational, meaning that no method of the component may be called unless a long-running conversation is active. @PerNestedConversation @PerNestedConversation Limits the scope of a CONVERSATION-scoped component to just the parent conversation in which it was instantiated. The component instance will not be visible to nested child conversations, which will get their own instance. Warning: this is ill-defined, since it 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 this feature! @Startup @Scope(APPLICATION) @Startup(depends="org.jboss.seam.bpm.jbpm") Specifies that an application scope component is started immediately at initialization time. This is mainly used for certain built-in components that bootstrap critical infrastructure such as JNDI, datasources, etc. @Scope(SESSION) @Startup Specifies that a session scope component is started immediately at session creation time. * depends — specifies that the named components must be started first, if they are installed. @Install @Install(false) Specifies whether or not a component should be installed by default. The lack of an @Install annotation indicates a component should be installed. @Install(dependencies="org.jboss.seam.bpm.jbpm") Specifies that a component should only be stalled if the components listed as dependencies are also installed. @Install(genericDependencies=ManagedQueueSender.class) Specifies that a component should only be installed if a component that is implemented by a certain class is installed. This is useful when the dependency doesn't have a single well-known name. @Install(classDependencies="org.hibernate.Session") Specifies that a component should only be installed if the named class is in the classpath. @Install(precedence=BUILT_IN) Specifies the precedence of the component. If multiple components with the same name exist, the one with the higher precedence will be installed. The defined precendence values are (in ascending order): * BUILT_IN — Precedence of all built-in Seam components * FRAMEWORK — Precedence to use for components of frameworks which extend Seam * APPLICATION — Predence of application components (the default precedence) * DEPLOYMENT — Precedence to use for components which override application components in a particular deployment * MOCK — Precedence for mock objects used in testing @Synchronized @Synchronized(timeout=1000) Specifies that a component is accessed concurrently by multiple clients, and that Seam should serialize requests. If a request is not able to obtain its lock on the component in the given timeout period, an exception will be raised. @ReadOnly @ReadOnly Specifies that a JavaBean component or component method does not require state replication at the end of the invocation. @AutoCreate @AutoCreate Specifies that a component will be automatically created, even if the client does not specify create=true. 30.2. Annotations for bijection The next two annotations control bijection. These attributes occur on component instance variables or property accessor methods. @In @In Specifies that a component attribute is to be injected from a context variable at the beginning of each component invocation. If the context variable is null, an exception will be thrown. @In(required=false) Specifies that a component attribute is to be injected from a context variable at the beginning of each component invocation. The context variable may be null. @In(create=true) Specifies that a component attribute is to be injected from a context variable at the beginning of each component invocation. If the context variable is null, an instance of the component is instantiated by Seam. @In(value="contextVariableName") Specifies the name of the context variable explicitly, instead of using the annotated instance variable name. @In(value="#{customer.addresses['shipping']}") Specifies that a component attribute is to be injected by evaluating a JSF EL expression at the beginning of each component invocation. * value — specifies the name of the context variable. Default to the name of the component attribute. Alternatively, specifies a JSF EL expression, surrounded by #{...}. * create — specifies that Seam should instantiate the component with the same name as the context 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 undefined in all contexts. @Out @Out Specifies that a component attribute that is a Seam component is to be outjected to its context variable at the end of the invocation. If the attribute is null, an exception is thrown. @Out(required=false) Specifies that a component attribute that is a Seam component is to be outjected to its context variable at the end of the invocation. The attribute may be null. @Out(scope=ScopeType.SESSION) Specifies that a component attribute that is not a Seam component type is to be outjected to a specific scope at the end of the invocation. Alternatively, if no scope is explicitly specified, the scope of the component with the @Out attribute is used (or the EVENT scope if the component is stateless). @Out(value="contextVariableName") Specifies the name of the context variable explicitly, instead of using the annotated instance variable name. * value — specifies the name of the context variable. Default to the name of the component attribute. * required — specifies Seam should throw an exception if the component attribute is null during outjection. Note that it is quite common for these annotations to occur together, for example: @In(create=true) @Out private User currentUser; The next annotation supports the manager component pattern, where a Seam component that manages the lifecycle of an instance of some other class that is to be injected. It appears on a component getter method. @Unwrap @Unwrap Specifies that the object returned by the annotated getter method is the thing that is injected instead of the component instance itself. The next annotation supports the factory component pattern, where a Seam component is responsible for initializing the value of a context variable. This is especially useful for initializing any state needed for rendering the response to a non-faces request. It appears on a component method. @Factory @Factory("processInstance") public void createProcessInstance() { ... } Specifies that the method of the component is used to initialize the value of the named context variable, when the context variable has no value. This style is used with methods that return void. @Factory("processInstance", scope=CONVERSATION) public ProcessInstance createProcessInstance() { ... } Specifies that the method returns a value that Seam should use to initialize the value of the named context variable, when the context variable has no value. This style is used with methods that return a value. If no scope is explicitly specified, the scope of the component with the @Factory method 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 meaningful for factory methods which return a value. * autoCreate — specifies that this factory method should be automatically called whenever the variable is asked for, even if @In does not specify create=true. This annotation lets you inject a Log: @Logger @Logger("categoryName") 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 component class. The last annotation lets you inject a request parameter value: @RequestParameter @RequestParameter("parameterName") Specifies that a component attribute is to be injected with the value of a request parameter. Basic type conversions are performed automatically. * value — specifies the name of the request parameter. Default to the name of the component attribute. 30.3. Annotations for component lifecycle methods These annotations allow a component to react to its own lifecycle events. They occur on methods of the component. There may be only one of each per component class. @Create @Create Specifies that the method should be called when an instance of the component is instantiated by Seam. Note that create methods are only supported for JavaBeans and stateful session beans. @Destroy @Destroy Specifies that the method should be called when the context ends and its context variables are destroyed. Note that destroy methods are only supported for JavaBeans and stateful session beans. Destroy methods should be used only for cleanup. Seam catches, logs and swallows any exception that propagates out of a destroy method. @Observer @Observer("somethingChanged") Specifies that the method should be called when a component-driven event of the specified type occurs. @Observer(value="somethingChanged",create=false) Specifies that the method should be called when an event of the specified type occurs but that an instance 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. 30.4. Annotations for context demarcation These annotations provide declarative conversation demarcation. They appear on methods of Seam components, usually action listener methods. Every web request has a conversation context associated with it. Most of these conversations end at the end of the request. If you want a conversation that span multiple requests, you must "promote" the current conversation to a long-running conversation by calling a method marked with @Begin. @Begin @Begin Specifies that a long-running conversation begins when this method returns a non-null outcome without exception. @Begin(join=true) Specifies that if a long-running conversation is already in progress, the conversation context is simply propagated. @Begin(nested=true) Specifies that if a long-running conversation is already in progress, a new nested conversation context begins. The nested conversation will end when the next @End is encountered, and the outer conversation will resume. It is perfectly legal for multiple nested conversations to exist concurrently in the same outer conversation. @Begin(pageflow="process definition name") Specifies a jBPM process definition name that defines the pageflow for this conversation. @Begin(flushMode=FlushModeType.MANUAL) Specify the flush mode of any Seam-managed persistence contexts. flushMode=FlushModeType.MANUAL supports the use of atomic conversations where all write operations are queued in the conversation context until an explicit call to flush() (which usually occurs 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. This setting is ignored when nested=true is specified. * nested — specifies that a nested conversation should be started if a long-running conversation is already in progress. * flushMode — set the flush mode of any Seam-managed Hibernate sessions or JPA persistence 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 @End Specifies that a long-running conversation ends when this method returns a non-null outcome without exception. * beforeRedirect — by default, the conversation will not actually be destroyed until after any redirect has occurred. Setting beforeRedirect=true specifies that the conversation should be destroyed at the end of the current request, and that the redirect will be processed in a new temporary conversation context. * root — by default, ending a nested conversation simply pops the conversation stack and resumes the outer conversation. Setting root=true specifies that the root conversation should be destroyed which effectively destroys the entire conversation stack. If the conversation is not nested, the current conversation is simply ended. @StartTask @StartTask "Starts" a jBPM task. Specifies that a long-running conversation begins when this method returns a non-null outcome without exception. This conversation is associated with the jBPM task specified in the named request parameter. Within the context of this conversation, a business process context is also defined, for the business process instance of the task instance. * The jBPM TaskInstance will be available in a request context variable named taskInstance. The jPBM ProcessInstance will be available in a request context variable 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 JSF component. * flushMode — set the flush mode of any Seam-managed Hibernate sessions or JPA persistence contexts that are created during this conversation. @BeginTask @BeginTask Resumes work on an incomplete jBPM task. Specifies that a long-running conversation begins when this method returns a non-null outcome without exception. This conversation is associated with the jBPM task specified in the named request parameter. Within the context of this conversation, a business 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 request context variable named taskInstance. The jPBM org.jbpm.graph.exe.ProcessInstance will be available in a request context variable named 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 JSF component. * flushMode — set the flush mode of any Seam-managed Hibernate sessions or JPA persistence contexts that are created during this conversation. @EndTask @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 actual transition triggered will be the default transition unless the application has called Transition.setName() on the built-in component named transition. @EndTask(transition="transitionName") 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 after any redirect has occurred. Setting beforeRedirect=true specifies that the conversation should be destroyed at the end of the current request, and that the redirect will be processed in a new temporary conversation context. @CreateProcess @CreateProcess(definition="process definition name") Creates a new jBPM process instance when the method returns a non-null outcome without exception. 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 @ResumeProcess(processIdParameter="processId") Re-enters the scope of an existing jBPM process instance when the method returns a non-null outcome without exception. The ProcessInstance object will be available in a context variable named processInstance. * processIdParameter — the name a request parameter holding the process id. Default to "processId". @Transition @Transition("cancel") Marks a method as signalling a transition in the current jBPM process instance whenever the method returns a non-null result. 30.5. Annotations for use with Seam JavaBean components in a J2EE environment Seam provides an annotation that lets you force a rollback of the JTA transaction for certain action listener outcomes. @Transactional @Transactional Specifies that a JavaBean component should have a similar transactional behavior to the default behavior 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 that method. This annotation may be applied at either class or method level. Do not use this annotation on EJB 3.0 components, use @TransactionAttribute! @ApplicationException @ApplicationException Synonym for javax.ejb.ApplicationException, for use in a pre Java EE 5 environment. Applied to an exception to denote that it is an application exception and should be reported to the client directly(i.e., unwrapped). Do not use this annotation on EJB 3.0 components, use @javax.ejb.ApplicationException instead. * rollback — by default false, if true this exception should set the transaction to rollback only * end — by default false, if true this exception should end the current long-running conversation @Interceptors @Interceptors({DVDInterceptor, CDInterceptor}) Synonym for javax.interceptors.Interceptors, for use in a pre Java EE 5 environment. Note that this may only be used as a meta-annotation. Declares an ordered list of interceptors for a class or method. Do not use this annotations on EJB 3.0 components, use @javax.interceptor.Interceptors instead. These annotations are mostly useful for JavaBean Seam components. If you use EJB 3.0 components, you should use the standard Java EE5 annotation. 30.6. Annotations for exceptions These annotations let you specify how Seam should handle an exception that propagates out of a Seam component. @Redirect @Redirect(viewId="error.jsp") 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 @HttpError(errorCode=404) 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. * end — specifies that the long-running conversation should end, default to false. 30.7. Annotations for Seam Remoting Seam Remoting requires that the local interface of a session bean be annotated with the following annotation: @WebRemote @WebRemote(exclude="path.to.exclude") Indicates that the annotated method may be called from client-side JavaScript. The exclude property is optional and allows objects to be excluded from the result's object graph (see the Remoting chapter for more details). 30.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 annotations required for EJB interceptor definition. @Interceptor @Interceptor(stateless=true) Specifies that this interceptor is stateless and Seam may optimize replication. @Interceptor(type=CLIENT) Specifies that this interceptor is a "client-side" interceptor that is called before the EJB container. @Interceptor(around={SomeInterceptor.class, OtherInterceptor.class}) Specifies that this interceptor is positioned higher in the stack than the given interceptors. @Interceptor(within={SomeInterceptor.class, OtherInterceptor.class}) Specifies that this interceptor is positioned deeper in the stack than the given interceptors. 30.9. Annotations for asynchronicity The following annotations are used to declare an asynchronous method, for example: @Asynchronous public void scheduleAlert(Alert alert, @Expiration Date date) { ... } @Asynchronous public Timer scheduleAlerts(Alert alert, @Expiration Date date, @IntervalDuration long interval) { ... } @Asynchronous @Asynchronous Specifies that the method call is processed asynchronously. @Duration @Duration Specifies that a parameter of the asynchronous call is the duration before the call is processed (or first processed for recurring calls). @Expiration @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 @IntervalDuration Specifies that an asynchronous method call recurs, and that the annotationed parameter is duration between recurrences. 30.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 Seam component, 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 Seam component, and must implement javax.faces.validator.Validator. * id — the JSF validator id. Defaults to the component name. 30.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 @DataModel("variableName") Outjects a property of type List, Map, Set or Object[] as a JSF DataModel into the scope of the owning 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 in the PAGE context. @DataModelSelection @DataModelSelection Injects the selected value from the JSF DataModel (this is the element of the underlying collection, or the map value). If only one @DataModel attribute is defined for a component, the selected 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 DataModel Selection being injected, the associated DataModel will also be injected. In this case, if the property annotated with @DataModel is a getter method, then a setter method for the property must also be part 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 @DataModelSelectionIndex Exposes the selection index of the JSF DataModel as an attribute of the component (this is the row number of the underlying collection, or the map key). If only one @DataModel attribute is defined for a component, the selected value from that DataModel will be injected. Otherwise, the component 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. 30.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. @DataBinderClass @DataBinderClass(DataModelBinder.class) Specifies that an annotation is a databinding annotation. @DataSelectorClass @DataSelectorClass(DataModelSelector.class) Specifies that an annotation is a dataselection annotation. 30.12. Annotations for packaging This annotation provides a mechanism for declaring information about a set of components that are packaged together. It can be applied to any Java package. @Namespace @Namespace(value="http://jboss.com/products/seam/example/seampay") Specifies that components in the current package are associated with the given namespace. The declared namespace can be used as an XML namespace in a components.xml file to simplify application configuration. @Namespace(value="http://jboss.com/products/seam/core", prefix="org.jboss.seam.core") Specifies a namespace to associate with a given package. Additionally, it specifies a component name prefix to be applied to component names specified in the XML file. For example, an XML element named init that is associated with this namespace would be understood to actually refer to a component named org.jboss.seam.core.init. 30.13. Annotations for integrating with the servlet container 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 @Filter as a servlet filter. It will be executed by Seam's master filter. * @Filter(around={"seamComponent", "otherSeamComponent"}) Specifies that this filter is positioned higher in the stack than the given filters. * @Filter(within={"seamComponent", "otherSeamComponent"}) Specifies that this filter is positioned deeper in the stack than the given filters. Chapter 31. Built-in Seam components 31.1. Context injection components 31.2. Utility components 31.3. Components for internationalization and themes 31.4. Components for controlling conversations 31.5. jBPM-related components 31.6. Security-related components 31.7. JMS-related components 31.8. Mail-related components 31.9. Infrastructural components 31.10. Miscellaneous components 31.11. Special components This chapter describes Seam's built-in components, and their configuration properties. The built-in components will be created even if they are not listed in your components.xml file, but if you need to override default properties or specify more than one component of a certain type, components.xml is used. Note that you can replace any of the built in components with your own implementations simply by specifying the name of one of the built in components on your own class using @Name. 31.1. Context injection components The first set of built in components exist purely to support injection of various contextual objects. For example, the following component instance variable would have the Seam session context object injected: @In private Context sessionContext; 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. 31.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 displayed during the next render response phase that occurs in the current conversation. * add(String messageTemplate) — add a faces message, rendered from the given message 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 a message template defined in the Seam resource bundle which may contain EL expressions. * addFromResourceBundle(Severity severity, String key) — add a faces message, rendered from a message template defined in the Seam resource bundle which may contain EL expressions. * clear() — clear all messages. org.jboss.seam.faces.redirect A convenient API for performing redirects with parameters (this is especially useful for bookmarkable search results screens). * redirect.viewId — the JSF view id to redirect to. * redirect.conversationPropagationEnabled — determines whether the conversation will propagate across the redirect. * redirect.parameters — a map of request parameter name to value, to be passed in the redirect request. * execute() — perform the redirect immediately. * captureCurrentRequest() — stores the view id and request parameters of the current GET 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 all observers. * raiseAsynchronousEvent(String type) — raise an event to be processed asynchronously by the EJB3 timer service. * raiseTimedEvent(String type, ....) — schedule an event to be processed asynchronously by the EJB3 timer service. * addListener(String type, String methodBinding) — add an observer for a particular 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 the form #{...} 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. * 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. 31.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 a depth-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 search when 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 stringified 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 the supported locales listed in jsf-config.xml. * localeSelector.cookieEnabled — specifies that the locale selection should be persisted via a cookie. 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 stringified representation of the timezone. * timezoneSelector.cookieEnabled — specifies that the timezone selection should be persisted via a cookie. org.jboss.seam.international.messages A map containing internationalized messages rendered from message templates defined in the Seam 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 be persisted via a cookie. org.jboss.seam.theme.theme A map containing theme entries. All of these components are always installed. 31.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 * 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 the current conversation from the conversation switcher, conversation list, or breadcrumbs. * setDescription(String description) — sets the description of the current conversation to be displayed in the conversation switcher, conversation list, or breadcrumbs. * redirect() — redirect to the last well-defined view id for this conversation (useful after login 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 a pageflow (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 the conversation. 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. 31.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 * begin(String pageflowName) — begin a pageflow in the context of the current conversation * 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 users groups 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 when the 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 current conversation. * businessProcess.hasCurrentTask() — is a task instance associated with the current conversation? * businessProcess.hasCurrentProcess() — is a process instance associated with the current conversation. * createProcess(String name) — create an instance of the named process definition and associate it with the current conversation. * startTask() — start the task associated with the current conversation. * endTask(String transitionName) — end the task associated with the current conversation. * resumeTask(Long id) — associate the task with the given id with the current conversation. * resumeProcess(Long id) — associate the process with the given id with the current conversation. * transition(String transitionName) — trigger the transition. org.jboss.seam.bpm.taskInstance Manager component for the jBPM TaskInstance. org.jboss.seam.bpm.processInstance 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 is installed. 31.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 current principal. . 31.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 . 31.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 JNDI context (by setting the sessionJndiName property) or it can created from the configuration options 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 to the SMTP server. * org.jboss.seam.mail.mailSession.password — the password to use to connect to the SMTP server * org.jboss.seam.mail.mailSession.debug — enable JavaMail debugging (very verbose) * org.jboss.seam.mail.mailSession.ssl — enable SSL connection to SMTP (will default to port 465) org.jboss.seam.mail.mailSession.tls — by default true, enable TLS support in the mail session * org.jboss.seam.mail.mailSession.sessionJndiName — name under which a javax.mail.Session is bound to JNDI. If supplied, all other properties will be ignored. 31.9. Infrastructural components These components provide critical platform infrastructure. You can install a component which isn't installed 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 up session beans * org.jboss.seam.core.init.debug — enable Seam debug mode. This should be set to false when in production. You may see errors if the system is placed under any load and debug is enabled. * org.jboss.seam.core.init.clientSideConversations — if set to true, Seam will save conversation context variables in the client instead of in the HttpSession. * org.jboss.seam.core.init.userTransactionName — the JNDI name to use when looking up the JTA UserTransaction object. org.jboss.seam.core.manager Internal component for Seam page and conversation context management. Always installed. * org.jboss.seam.core.manager.conversationTimeout — the conversation context timeout in milliseconds. * org.jboss.seam.core.manager.concurrentRequestTimeout — maximum wait time for a thread attempting to gain a lock on the long-running conversation context. * org.jboss.seam.core.manager.conversationIdParameter — the request parameter used to propagate the conversation id, default to conversationId. * org.jboss.seam.core.manager.conversationIsLongRunningParameter — the request parameter used to propagate information about whether the conversation is long-running, default to conversationIsLongRunning. * org.jboss.seam.core.manager.defaultFlushMode — set the flush mode set by default on any Seam Managed Persistence Context. By default AUTO. org.jboss.seam.navigation.pages Internal component for Seam workspace management. Always installed. * org.jboss.seam.navigation.pages.noConversationViewId — global setting for the 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 to redirect to when an unauthenticated user tries to access a protected view. * org.jboss.seam.navigation.pages.httpPort — global setting for the port to use when the http scheme is requested. * org.jboss.seam.navigation.pages.httpsPort — global setting for the port to use when 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 jPDL files to be used for orchestration of business processes. * org.jboss.seam.bpm.jbpm.pageflowDefinitions — a list of resource names of jPDL files to be used for orchestration of conversation page flows. org.jboss.seam.core.conversationEntries Internal session-scoped component recording the active long-running conversations between requests. 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 current conversation. org.jboss.seam.jms.queueConnection Manages a JMS QueueConnection. Installed whenever managed managed QueueSender is installed. * 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 is installed. * 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 management implementation 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 action expression exists in the view. 31.10. Miscellaneous components These components don't fit into org.jboss.seam.async.dispatcher Dispatcher stateless session bean for asynchronous methods. org.jboss.seam.core.image 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. 31.11. Special components Certain special Seam component classes are installable multiple times under names specified in the Seam configuration. For example, the following lines in components.xml install and configure two Seam components: java:/comp/emf/bookingPersistence java:/comp/emf/userPersistence The Seam component names are bookingDatabase and userDatabase. , org.jboss.seam.persistence.ManagedPersistenceContext Manager component for a conversation scoped managed EntityManager with an extended persistence context. * .entityManagerFactory — a value binding expression that evaluates to an instance of EntityManagerFactory. .persistenceUnitJndiName — the JNDI name of the entity manager factory, default to java:/. , org.jboss.seam.persistence.EntityManagerFactory Manages a JPA EntityManagerFactory. This is most useful when using JPA outside of an EJB 3.0 supporting environment. * entityManagerFactory.persistenceUnitName — the name of the persistence unit. See the API JavaDoc for further configuration properties. , org.jboss.seam.persistence.ManagedSession Manager component for a conversation scoped managed Hibernate Session. * .sessionFactory — a value binding expression that evaluates to an instance of SessionFactory. .sessionFactoryJndiName — the JNDI name of the session factory, default to java:/. , org.jboss.seam.persistence.HibernateSessionFactory Manages a Hibernate SessionFactory. * .cfgResourceName — the path to the configuration file. Default to hibernate.cfg.xml. See the API JavaDoc for further configuration properties. , org.jboss.seam.jms.ManagedQueueSender Manager component for an event scoped managed JMS QueueSender. * .queueJndiName — the JNDI name of the JMS queue. , org.jboss.seam.jms.ManagedTopicPublisher Manager component for an event scoped managed JMS TopicPublisher. * .topicJndiName — the JNDI name of the JMS topic. , org.jboss.seam.drools.ManagedWorkingMemory Manager component for a conversation scoped managed Drools WorkingMemory. * .ruleBase — a value expression that evaluates to an instance of RuleBase. , org.jboss.seam.drools.RuleBase Manager component for an application scoped Drools RuleBase. Note that this is not really intended for production usage, since it does not support dynamic installation of new rules. * .ruleFiles — a list of files containing Drools rules. .dslFile — a Drools DSL definition. , org.jboss.seam.framework.EntityHome , org.jboss.seam.framework.HibernateEntityHome , org.jboss.seam.framework.EntityQuery , org.jboss.seam.framework.HibernateEntityQuery Chapter 32. Seam JSF controls 32.1. Tags 32.1.1. Navigation Controls 32.1.2. Converters and Validators 32.1.3. Formatting 32.1.4. Seam Text 32.1.5. Dropdowns 32.1.6. Other 32.2. Annotations Seam includes a number of JSF controls that are useful for working with Seam. These are intended to complement the built-in JSF controls, and controls from other third-party libraries. We recommend JBoss RichFaces, ICEsoft ICEfaces and Apache MyFaces Trinidad tag libraries for use with Seam. We do not recommend the use of the Tomahawk tag library. 32.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. 32.1.1. Navigation Controls 32.1.1.1. Description A button that supports invocation of an action with control over conversation propagation. Does not submit 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 . In this case, the action will be called once the redirect to the specified view has occured. The use of action listeners (including the default JSF action listener) is not supported with . 32.1.1.2. Description Add the conversation id to JSF link or button (e.g. , ). Attributes None 32.1.1.3. Description Add the task id to an output link (or similar JSF control), when the task is available via #{task}. Attributes None. 32.1.1.4. Description A link that supports invocation of an action with control over conversation propagation. Does not submit the form. The use of action listeners (including the default JSF action listener) is not supported with . 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 . In this case, the action will be called once the redirect to the specified view has occured. 32.1.1.5. Description Customize the conversation propagation for a command link or button (or similar JSF control). Facelets only. 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 32.1.1.6. 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. , or ). You must specify an id on the action source. You can only have one default action per form. Attributes None. Usage 32.1.2. Converters and Validators 32.1.2.1. Description Perform date or time conversions in the Seam timezone. Attributes None. Usage 32.1.2.2. Description Assigns an entity converter to the current component. This is useful for radio button and dropdown controls. The converter works with any managed entity - either simple or composite. The converter should be able to find the items declared in the JSF controls on form submission, otherwise you will receive a validation error. Attributes None. Configuration You must use Seam managed transactions (see Section 9.2, “Seam managed transactions”) with . If your Managed Persistence Context isn't called entityManager, then you need to set it in components.xml: If you are using a Managed Hibernate Session then you need to set it in components.xml: If your Managed Hibernate Session isn't called 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 of the entity converter for each entity manager in components.xml - note how the entity converter delegates to the entity loader to perform persistence operations: Usage 32.1.2.3. Description Assigns an enum converter to the current component. This is primarily useful for radio button and dropdown controls. Attributes None. Usage 32.1.2.4. Description javax.faces.convert.Converter for java.util.concurrent.atomic.AtomicBoolean. Attributes None. Usage 32.1.2.5. Description javax.faces.convert.Converter for java.util.concurrent.atomic.AtomicInteger. Attributes None. Usage 32.1.2.6. Description javax.faces.convert.Converter for java.util.concurrent.atomic.AtomicLong. Attributes None. Usage 32.1.2.7. Description Tag to nest inside an input control to validate that its parent's value is equal (or not equal!) to the referenced control's value. Attributes * for — The id of a control to validate against. * message — Message to show on failure. * messageId — Message id to show on failure. * operator — What operator to use when comparing the values Valid operators are: o equal — Validates that value.equals(forValue) o not_equal — Validates that !value.equals(forValue) o greater — Validates that ((Comparable)value).compareTo(forValue) > 0 o greater_or_equal — Validates that ((Comparable)value).compareTo(forValue) >= 0 o less — Validates that ((Comparable)value).compareTo(forValue) < 0 o less_or_equal — Validates that ((Comparable)value).compareTo(forValue) <= 0 Usage 32.1.2.8. Description A non-visual control, validates a JSF input field against the bound property using Hibernate Validator. Attributes None. Usage 32.1.2.9. Description A non-visual control, validates all child JSF input fields against their bound properties using Hibernate Validator. Attributes None. Usage
Username:
Password:
Verify Password:
32.1.3. Formatting 32.1.3.1. 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 if you have set the input component being decorated as required, and #{invalid} evaluates to true if a validation error occurs. Usage Country:
*
32.1.3.2. Description Render a HTML
. Attributes None. Usage Sorry, but this member does not exist. 32.1.3.3. Description Render a HTML . Attributes * title — Title for a span. Usage * 32.1.3.4. Description A non-rendering component useful for enabling/disabling rendering of it's children. Attributes None. Usage Current bid: 32.1.3.5. Description "Decorate" a JSF input field with the label. The label is placed inside the HTML