Category Archives: J2EE

A keyword and answer session

jboss seam session vs conversation: A Session is a standard Servlet concept – a collection of attributes that the server maintains while a user is active on web application. Applications leverage it heavily to store server-side the current state of the user – such as the contents of his or her shopping basket. There are other collections – for example, those associated with a single HTTP request. Seam takes this several steps further. Each of these original collections has it’s place in Seam as a Context, along with several new ones that Seam uses and provides. This sounds onerous, but in Seam you no longer have to know that the attribute you want is stored in the session, you can instead just ‘inject’ the attribute, and Seam will find it for you from any of the contexts it supports.

One of these contexts is the Seam conversation context. It doesn’t last as long as a the user’s Session, by default timing out after 5 minutes of inactivity, but it’s lifetime is entirely managed by the Seam framework, avoiding the messiness that comes with losing all the user-specific state you left in an expired Session when a user resumes activity.

Naturally just as an application may manage multiple concurrent user sessions, Seam lets you have multiple conversations per user session. A widely used analogy is that of a workspace; in our case we have one workspace for each document that our users may be editing.

I can only speak about JSF, as Seam supports several view layers; but here Seam really shines. In JSF plain, managed beans have to be declared in faces-config.xml. In Seam, a custom EL resolver evaluates EL statements (#{}) and dynamically identifies from the Seam contexts which bean to use. This process is similar to injection, and so Seam is able to look up any bean stored in any of it’s contexts, or even create on the fly an instance of properly annotated java class. So – no more faces-config.XML.

With the custom EL resolver and a heirarchical context search, Seam allows you to write beans and pages that work in the context of a particular workspace (conversation). When a page is rendered, Seam knows what conversation that page is being rendered in, and so it can dynamically pull the correct bean instances from the correct conversation context instance.

Part of the state of a conversation is what page you are looking at in an application. Seam conversations can be used for a limited form of page flow. This is because not only can a user have multiple conversations per session, but conversations can also be nested. By creating a nested conversation, the parent conversation is frozen along with the view the user was last looking at while in that conversation. When a user causes the nested conversation to end, Seam can return the user to the parent conversation and also to the page they were on before the user entered into the scope of the nested conversation. Conversations can be arbitrarily nested, and attributes of the parent conversation are available to the nested conversations through injection and EL resolution. The process of searching contexts for attributes is known as the hierarchical context search in Seam.

Lastly, I should mention that there is always a Seam conversation in place. This differs from explicitly created ‘long running conversations’ in that it is temporary and lives only for the duration of postback + possible redirect. This temporary conversation is used by Seam to traffic JSF Faces Messages through a redirect. For example, say you have a page with a button, and when you click that button you trigger an error. But you want the specific error to be displayed on another page. The postback for the button could redirect the user to the error handling page, but in standard JSF you would lose the specific error message stored in the FacesMessages object. Seam keeps those messages in the conversation context so that it doesn’t matter what page renders the result of the user’s interaction – the messages will still be available. This is just one example where the conversations helps Seam smooth over JSF’s wrinkles.

no active conversation context: With the above knowledge, this exception should now be easy to understand. Take the example of a deep bookmark saved from a Seam web application. Let’s say that this page was bookmarked from the a ticket reservation system, and because of this it relies on beans that exist only while tickets are temporarily reserved for purchasing. These beans could reasonably be marked @Conversational or otherwise explicitly scoped to the Conversation contexts as even just 5 minutes later, the tickets would no longer reserved for purchasing. (In this case the 5 minute expiry of the conversation is tied to the business process, however all conversations in Seam expire). If the user navigates to this deep bookmark after the conversation has expired, then this exception will be thrown.

You have a couple of options to work around this exception:
1) Increase the conversation timeout in components.xml, or more likely
2) Trap the exception in pages.xml and redirect the user to a page that will let them restore or restart their activity.

(And for the record, yes, the keywords that caused me to write these articles were listed as incoming searches using google analytics )

Optimizing Richfaces AJAX a4j

Just a quick post because there doesn’t seem to be much on the web about this.

RichFaces AJAX library, originally a separate project called Ajax4JSF, is a well integrated engine for AJAX-enabling a JSF web page.

The library adapts standard JSF/HTML forms so that the POST is sent back to the server via a background request (e.g. XmlHttpRequest ). All requests handled by the server are wrapped in a filter that runs what is mostly the normal JSF lifecycle. The response is then processed by the filter to encode aspects of the JSF response that are not in the returned HTML – like HTTP redirects. This post-processed response is returned to the client which then parses the response and applies it to the page, updating elements, triggering redirects, and so on.

This is fast because JSF builds and holds an in-memory representation of the web page through out the page lifecycle, so the original JSF page does not need to be re-parsed.

Never-the-less, there’s always a need for more speed, and as you expand your AJAX enabled page to include more and more dynamic controls, you may encounter some slow down as both the server and the client need to parse more and more data.

In our application, and on a single page, we have 20 externally included sections, each with a couple of independent forms, and a corresponding number of modal panels, again each with their own forms. Since these forms have been independently developed, performance issues have arisen.

Luckily the designers of the AJAX enabled components within Richfaces have kept this in mind and have provided a full set of attributes that allow you to control what is included in the AJAX lifecycle. Unfortunately, the documentation is somewhat sparse on the various core attributes and how they interact so I hope to use this page to detail how these tags can be used together to optimize the AJAX JSF lifecycle. It’s a work in progress that I will populate as a I update our application.

Core Lifecycle Tags


Behaviour Tag Applies to Performance impact
Establish an AJAX form a4j:form JSF page When any AJAX event defined within an a4j:form is submitted – only form fields from within that form will be submitted. This is the only way to limit the data sent to the server.
Restrict server-side processing a4j:region JSF page Isolate a section of the component tree so that during the AJAX request the server only has to process a subset of the page. Attributes on this tag identify how that isolation affects the individual JSF phases – including determining what is to be included in the HTTP AJAX response. selfRendered appears to disregard non-verbatim code, but it may work well with Facelets since it already stores HTML in the component tree.
Identify a dynamic output region a4j:outputPanel JSF page The outputPanel marks a place in the component tree for which the server might send a response, and thus for which the client may have to perform a partial page update. Setting the ajaxRendered=true attribute on this tag bloats all AJAX request from the page and thus slows client and server processing.


In the next post I will follow up with information about the attributes on these tags. Several attributes on the above tags interact with each other; for example what is the effect of combining a form inside an a4j:region renderRegionOnly=”true” and a4j:outputPanel ajaxRendered=”true”?

JBoss Seam and conversation boundaries

In the web site we are building we have a set of search pages to identify records, and a long list of CRUD pages for various aspects of those records. This section of the application looks and feels just as a standard web application, where as a user you are engaged in only one activity at a time and none of the business transactions you engage in span more than a single database transaction (unlike, say, a wizard).

Another section of the application works completely differently – it is a document editor that can edit complex structured documents associated with records in the system. This cries out for the ability to have multiple editors available, which is exactly the kind of thing that can be modeled by a Conversation in Seam .

Supporting the document editor feature we have several command buttons distributed throughout the application that allow you to add, edit, or view (in PDF form) these documents.  Once in a document editor, you can leave the editor, visiting the rest of the application, and resume it with a click of a button.

Implementing this turned out to be a little trickier than expected and required a solid understanding of conversation boundaries, or when a conversation comes into existence, and when it leaves.

Here are the key players in the architecture:


So the navigation flow is very simple – the user visits a search results page, and from there opens an editor. In between the visit to the search-results page and the editor being ready to use in the browser,  the various other components shown are accessed. I’ve explicitly omitted conversation boundaries from this diagram since there are so many ways to start and stop the conversation and it’s the core of what I want to talk about.

In the diagram, the component classes are omitted since they are irrelevant in Seam.

  • editorCollection: Keep track of conversations associated with specific documents.
  • search-results.xhtml: Display a list data items, each with action buttons.
  • editorActions: Contains the code backing the buttons in search-results.xhtml, acts on documents before they are being edited.
  • document: An entity instance of a document being edited or viewed
  • editorManager: Contains the code backing the buttons in editor.xhtml, allowing operations to be performed on a document while it is being edited.
  • editor.xhtml: The actual editor page – consists of a range of buttons to act on the document or to leave the editor, along with document specific widgets that allow data to be entered into the document.
  • pages.xml: This is the global Seam page configuration file, similar to faces-config.xml in JSF.


pages.xml is the central piece that establishes navigation among pages in terms of responses to actions triggered by buttons on the page. A simple example might simply be:

<page view-id="search-results.xhtml">
<navigation from-action="#{editorActions.edit(documentId)}">
<redirect view-id="editor.xhtml" />

This action would correspond to a link from search-results.xhtml:

[xhtml]<s:link action="#{editorActions.edit(documentId)}" />[/xhtml]

The from-action attribute in pages.xml is not executed – it simply identifies the operation that the navigation rule applies to by being the same exact string. When the link is clicked, the edit() function is executed, and the editor.xhtml view is loaded.

Starting a conversation

This navigation rule and the code listed so far does not actually start a conversation, which means that anything the edit() function does is going to do will act on the session as a whole (since it is a Seam SESSION component). So we have no segregation between document editor instances.

Ignoring the ability to declare that a conversation is required (that’s really just defensive coding, and who wants to see exception handling code?); there are three main places you can instruct Seam to start up a conversation:

* Java 1.5 Annotations provided by Seam (@Begin) on the components
* Attributes on s:link and s:button or tags applied to JSF components; all provided by the Seam UI tag library
* Within page rules in pages.xml using directives like

There are good reasons for using each, but the necessarily page and component spanning nature of conversations make the third option a good choice. The declarative features of pages.xml allow the start and end points of conversations to be placed in a single file, centralizing the lifetime of a conversation, while still allowing the option of implementing conditional navigation logic with EL expressions.

Document editor pages.xml with conversations

<page view-id="search-results.xhtml">
<navigation from-action="#{editorActions.edit(documentId)}">
<start-conversation />
<redirect view-id="editor.xhtml" />
<page view-id="editor.xhtml">
<navigation from-action="#{editorManager.discard()}">
<end-conversation />
<redirect view-id="search-results.xhtml" />

This simple fragment easily shows the ability to cycle between the two pages, starting a conversation before being in the editor and ending a conversation when leaving.

Exactly when does a conversation come to exist?

Upon a click from the search results page, an action method on the editorActions component is invoked. Since the editorAction methods are working on any of the iterated search results, we need to pass the selected record to the action method.

This data is the documentId of the document being edited, (or equivalently the documentTypeId of the document being added). Using this parameter we retrieve from persistence all the data required to display and format the document. Obviously all this information needs to be scoped to the current conversation context in order for it to be segregated from other instances of editors.

Which poses the question: is the conversation context active when the editorActions.edit(documentId) method is executing? If the answer is yes, we should be able to place variables into the conversation context from within editorActions.edit(documentId).

Unfortunately for our system the answer is no, which means this code is bad:

[java]import org.jboss.seam.annotations.*;
import static org.jboss.seam.ScopeType.*;
@Name("editorActions") public class EditorActions {
@In(required = false)
Conversation conversation;
public void edit(int documentId)
assert conversation != null;
// record the conversation editor instance

We find that during this method, access to the conversation object is unavailable. The obvious inference is that there is no active Seam conversation at this time.

Now it is possible that the tag in pages.xml acts differently to placing an @Begin annotation on an action method. However, the following code acts no differently:

[java]@Begin public void edit(int documentId)
assert conversation != null;
// record the conversation editor instance

The problem, and neglected alternate approaches

Event with a conversation context in place, the code performs a significant amount of startup of other components that rely on Conversation scoped data, but because Seam manages outjection through interceptors around method calls, any @Out annotated variables will not actually be placed into the conversation scope until the method returns. So all those other components cannot perform the work they need to do in response to code in the editorActions.edit(documentId) action method.

The issue could be resolved by starting the conversation on one page, and redirecting the user to a temporary page in which a document is not yet loaded, but in which the Seam conversation is fully active. We have tried this approach before, but routing the user indirectly does not give the application the slick feel we are looking for.

One thing we tried when creating a workaround that would allow us to place the loaded document into the conversation context was to observe the built-in seam event that is fired when a new conversation is created. This turned out to be a complicated path to take because the component dealing with creating the document is in the SESSION scope, meaning that it synchronized by Seam to ensure that there are no concurrent accesses. This prevented our observer from interacting with the session scoped editorActions bean as the action method was already executing.

Establishing and populating a Seam conversation context in one go

What we finally tried and have discovered to work well is to access directly the Conversation context from within the editorAction.edit(documentId) method:

[java]public void edit(int documentId)
Document d = loadDocument(documentId);
Context conversationContext = Contexts.getConversationContext();
conversationContext.set("documentData", d);

The d.activate() function can access conversation scoped variables manually placed in the conversation context by this method, despite the conversation not having been fully created, and despite any outjections (@Out annotated variables) not having yet been processed.

This is inline with Seam’s published behaviour in which there is always a conversation context present, but that it is temporary unless it has been converted to a long running conversation.

Final Solution

In the end we opted to leverage the Seam @Begin annotation on the editorActions methods that trigger a switch to an editor.  In this manner we ensure the creation of a Conversation is co-located with the functionality that is so tightly coupled to it. We did not do the same for the end of the conversation, since there are various buttons and links on the editor that assist with leaving the page, not all of which have action methods associated with them.  In addition, we decided to sink exceptions and internally log and email them, and altered the action methods to return an outcome string. This allows us to conditionally return to the results page if an error occurs creating an editor and also be able to display an appropriate message. This works nicely with Richfaces/A4J .

The pages.xml now looks like this:

<page view-id="search-results.xhtml">
<navigation from-action="#{editorActions.edit(documentId)}">
<rule if-outcome="success">
<redirect view-id="editor.xhtml" />
<rule if-outcome="bad-template">
<message severity="ERROR">Failed to create the editor because template #{errorTemplate} is broken</message>
<page view-id="editor.xhtml">
<navigation from-action="#{editorManager.discard()}">
<end-conversation />
<redirect view-id="search-results.xhtml" />

As was mentioned above, we also opted to create a separate editorCollection bean. This bean was necessary purely to avoid concurrent access to a single Seam component. When a conversation is created, this bean manages the process of figuring out a human readable name for the conversation for use in conversation switcher components (i.e., to switch editors).

More on concurrent access to conversation components

As I’ve noted, a SESSION scoped bean cannot be accessed concurrently. Really, no Seam component can be treated as re-entrant. Synchronization on SESSION components is provided to you by Seam because it is likely that a user may double click a link or otherwise trigger multiple concurrent requests. Seam components in lower scopes like PAGE and EVENT do not need synchronization since there will be multiple instances of them created to respond to each activity.

CONVERSATION scoped components are synchronized by Seam by locking the whole conversation while the request is ongoing. New requests for the same conversation are blocked for up to 500ms (configurable), and if the conversation is still not free, then Seam returns a message. In my experience, those web requests received a blank document.

This is critical to understand if you need to make back-end round-trip requests to the web server – you cannot use the same conversation for those. But that’s a topic for another time.