Thoughts on…

Java Middleware & Systems Management

Archive for the ‘webdev’ Category

Web Development Tips – automate the little things

with 3 comments

I recall a colleague of mine mentioning several weeks ago that it’s annoying to have to log into RHQ every time you redeploy UI code that causes portal-war’s web context to reload. I completely agreed at the time, but it wasn’t until today that I finally got annoyed enough to look for a workaround myself. Here’s the solution I ended up with:

1) Use FireFox
2) Download and install GreaseMonkey
3) Install the AutoLogin script
4) Log into “http://localhost:7080/” and make sure to tell FF to remember your password
5) Test that auto-login is working properly by logging out of the application…you should be forwarded to the login page, which FF will automatically fill in with your saved credentials, and the grease monkey script will perform the login for you

This should also work when you get logged out due to session expiry. The expiry handler will redirect you back to /, which will now automatically log you back in and – on a best effort basis – redirect you back to the last “valid” page you were on. RHQ has a mechanism for recording the last couple of pages you visited (see WebUserTrackingFilter) and will try them in most-recently-visited order until it finds a page that doesn’t blow up with JSF’s “classic” ViewExpiredException. I discuss the details of how this mechanism works in my other post.

Note: if you ever want to log into localhost with a different user, all you have to do is click the GreaseMonkey icon (on the far right-hand side of the status bar at the bottom of your browser) and you’ll temporarily disable the AutoLogin script from executing.

How would you solve this? How have you solved this? I’m eager to read your post backs.


Written by josephmarques

February 5, 2010 at 4:19 pm

Posted in webdev

Tagged with

Custom JSF/Facelet Exception Handling

with 13 comments

Have you ever used a JSF-based application, navigated to some page, only to see a nasty error?

This is what you get out-of-box with facelets. Most of the time it happens when the facelet tries to resolve some EL expression, needs to create some JSF managed bean, but one or more required URL parameters are either missing or have invalid values.

In a development environment, it makes sense to show this page because the various pieces of contextual information (full stack trace + JSF component tree + variables in scope) provide plenty of clues with which to diagnose the issue. However, when you ship a product to a customer or push your changes to a production environment, it would be nice to change the behavior and provide a pleasant error page to the user.

Fortunately, the facelets framework makes overriding this default behavior incredibly simple. The basic premise is to redirect to a custom error page so you can provide a layout that hides the unappealing stack trace, but which still provides a link to view those details (primarily so your customers can report the bugs back to you).

Note: the following code examples will be pulled directly from the RHQ / Jopr code base.

The first step is to add a custom view handler to your web application. Open up the faces-config.xml file and add a custom view handler:

<faces-config ...>

Then override the default mechanism for dealing with errors that the facelet framework encounters:

public class FaceletRedirectionViewHandler extends FaceletViewHandler {
    protected void handleRenderException(FacesContext context, Exception ex) throws IOException, ELException,
        FacesException {
        try {
            if (context.getViewRoot().getViewId().equals("/rhq/common/error.xhtml")) {
                 * This is to protect from infinite redirects if the error
                 * page itself is updated in the future and has an error
                log.error("Redirected back to ourselves, there must be a problem with the error.xhtml page", ex);

            getSessionMap().put("GLOBAL_RENDER_ERROR", ex);
        } catch (IOException ioe) {
            log.fatal("Could not process redirect to handle application error", ioe);

View full source here

The basic strategy is capture the exception and redirect to your new error page. However, what if there is a compile error on the error page itself? Your new error handling code would capture that error and try to handle it, which would redirect back to the custom error page which still has that error on it! This leads to an infinite redirect, which all modern browsers can and will detect, but it doesn’t provide much useful information as to what error occurred on the page.

You might be asking yourself, “How likely is it that the error page will have an error?” Well, this could happen either as you’re writing the page for the first time, or are updating the page in the future to add other features. Fortunately, there is an easy way of protecting against this. In your error handling code, simply test which JSF viewId you’re coming from and, if it’s your new error page, then revert back to the default handler by calling the superclass method being overridden. Don’t forget to explicitly break/return out of the custom handler, otherwise you’ll still see the infinite recursion.

The next and final step is to write the logic that pulls the exception back out of the session map on the other side of the redirect:

public class GenericErrorUIBean {
    String summary; // the name of the exception class, usually self-descriptive
    String details; // a little more information about the named exception
    List<Tuple> trace; // fine-grained trace details

    public GenericErrorUIBean() {
        trace = new ArrayList<Tuple>();
        Throwable ex = (Exception) getSessionMap().remove("GLOBAL_RENDER_ERROR");

        String message = ex.getLocalizedMessage();
        String stack = StringUtil.getFirstStackTrace(ex);
        trace.add(new Tuple(message, stack));
        while (ex.getCause() != null) {
            ex = ex.getCause();
            message = ex.getLocalizedMessage();
            stack = StringUtil.getFirstStackTrace(ex);
            trace.add(new Tuple(message, stack));

        summary = ex.getClass().getSimpleName();
        details = ex.getMessage();

    private static String getFirstStackTrace(Throwable t) {
        if (t == null) {
            return null;
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        return sw.toString();

View full source here

Depending on what you want your error page to look like, you can use a variety of methods for chopping up the stack trace into more manageable and/or user-friendly bits. In this case, the solution I used for the RHQ platform loops over the full trace one stack frame at a time. At each frame, we record the name of the exception-class and map that to the exception-stack at that frame. In this fashion, we can generate of list of tuples which can be iterated over in our error.xhtml facelet with either the ui:repeat or a4j:repeat tag.

The end result is a page that looks at professional by hiding the ugly errors and showing the root cause in small, easy to understand language.
Note, however, that the page can still be used as a debugging tool. See the “view the stack trace” link at the bottom? Clicking it opens up a modal dialog which display the full stack trace (which is useful for reporting bugs through customer support [for downloaded products], or emailing the webmaster [for hosted applications]).

For brevity, the source code of the error.xhtml facelet has been left out of this blog entry, but you can view the full source here

This is just one of the many solutions employed by the RHQ platform to provide a great web driven interface that centralizes the monitoring and management of your enterprise systems. To find out more, please visit one of the links below:

RHQ (base management platform) –
Jopr (Jboss specific extensions to RHQ) –

Written by josephmarques

April 27, 2009 at 7:29 am

Posted in webdev

Tagged with

JSF Odyssey – ViewExpiredException

with 9 comments

For any developer that has used JSF for even a week, you know exactly what the title of this entry is referring to.

A quick google search for “ViewExpiredException” finds users complaining about this on threads from all different sorts of vendors: Oracle, Apache, IceFaces, MyFaces, JBoss. And that’s just the first 10 entries! But the fault does not lie with any of these vendors. The dreaded ViewExpiredException is most likely the result of the fact that you’re interacting with (or developing) a user-authenticated, web-based application written in JSF. If you’re logged in and your HTTP session expires, JSF will quite annoyingly throw ViewExpiredException during the RESTORE_VIEW phase of the JSF life cycle – it’s a feature!

During my wanderings I’ve seen people try to solve this issue in a variety of ways. Some try to use global Exception handling in the web.xml file for their WAR. Others try to use a pure JSF-based solution whereby a PhaseListener can attempt to perform a response redirect during the RESTORE_VIEW phase. Even JBoss Seam tries to solve this in their own way using their exception handlers in the components.xml file.

However, none of these solutions are complete in my opinion. All of them seem to ignore one completely obvious question – how do I redirect the user back to the LAST page they were on before the session timed out? Without this piece, the usability of the site goes way down and, as most of these solutions will proffer, the user has to start at the site’s main entry point again.

Restoring the last visited JSF view, however, is easier said than done. The HTTP POST-based nature of the framework makes it very difficult to capture the needed state / context prior to the timeout. It doesn’t really matter if you record the last accessed path if you don’t have the appropriate URL parameters to pass to it after the user logs back in. So, the only proper fix for this is to extend JSF in some way to provide RESTful site interactions.

Luckily, there are frameworks which (to different degrees) provide RESTful concepts, such as JBoss Seam with bookmarkable URLs or RestFaces with the enablement of HTTP GET in your JSF environment. Unfortunately, the RHQ Project needed one of these solutions in early ’06, and those frameworks either didn’t exist or were still being incubated at the time. So, necessity being the father of invention, we wrote our own mechanism. It can be summarized as follows:

1) Redirects across all form submission boundaries
2) Custom JSF navigation handler that performs EL resolution of “enhanced” viewIds

With it, a standard JSF navigation rule then looks like:


Granted, the syntax is not all that inviting, but it gets the job done. Nearly every single page flow in RHQ starts and ends with a URL specifying representational state explicitly in its parameter map. And from a developer’s perspective, the slightly modified navigation rule is likely the only modification that has to be made. Most of the time the visible form elements (on the form leading up to the enhanced navigation rule) will be a superset of the state that will be resolved, in which case you’re done. However, if you need to propagate additional state, you can always include an unlimited number of hidden form inputs to submit your extra context information.

The bulk of the logic for how this all works is hidden behind various extensions that were made to the JSF framework. Since we’re crossing redirect boundaries, any errors that your managed bean would have placed in the FacesContext would normally be lost. But this was taken into consideration and is handled in a 3-step process by a custom phase listener:

* Step 1: capture any messages put in the GLOBAL faces messages context, and save them to the session at the end of biz tier processing
* Step 2: before the processing continues on the other side of the redirect boundary, copy the save elements back into the GLOBAL faces context
* Step 3: clear out the area of the session used for this message propagation

For those that understand better by seeing the code:

public class FacesMessagePropogationPhaseListener 
implements PhaseListener {
    public PhaseId getPhaseId() {
        return PhaseId.ANY_PHASE;
    public void beforePhase(PhaseEvent event) {
        if (event.getPhaseId() == PhaseId.RESTORE_VIEW) {
            List savedMessages = 
            // step2: retrieve 'em
    public void afterPhase(PhaseEvent event) {
        if (event.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
            // step1: save 'em
        } else if (phaseId == PhaseId.RENDER_RESPONSE) {
            // step3: delete 'em

The only thing left to do is to override the standard navigation handler with one performs variable resolution:

public class FaceletRedirectionViewHandler 
extends FaceletViewHandler {
    // Evaluate any EL variables contained in the view id.
    public String getActionURL(FacesContext facesContext, 
    String viewId) {
        FacesContext facesContext = 
        ELContext elContext = facesContext.getELContext();
        ExpressionFactory factory = 
        ValueExpression valueExpression = 
                viewId, String.class);
        String resolvedActionURL = 
            (String) valueExpression.getValue(elContext);
        return resolvedActionURL;

What was this blog about again? Oh, yes, that’s right – ViewExpiredException. Although this mechanism concerning URL resolution might have seemed like a tangent to the problem at hand, it was necessary groundwork that had to be laid, which now gives us the tools to undo the damage caused by a lifecycle “feature” of our component framework. As you navigate around the site now, your URL history will look something like:


All you have to do is record the last URL the user was on; if at any point the ViewExpiredException occurs, simply redirect back to that last URL. The RHQ platform uses standard error handling in the web.xml to forward to a JSP page that then has the logic to call and redirect the response writer to this saved value. If you rely on the browser’s history as the storage mechanism, then recalling that last URL only takes one line of javascript:


Note: you may have to use either -1 or -2 as the argument to the ‘go’ method, depending on whether the user was attempting to access a secured page (which might have redirected to some authenticating servlet before redirecting you back to the requested URL where the ViewExpiredException was thrown from)

Using the browser’s history also has the advantage of operating quite naturally in a multi-window (or multi-tab) environment. If you want your users to be able to navigate around your application using multiple windows, the browser history will provide natural isolation of these individual browsing histories. This way, regardless of which tab the user is on when they experience the ViewExpiredException, they are redirected back to the last page they are on *within that window* (as opposed to the last accessed page in any of that user’s open windows).

If it wasn’t already apparent, the key factor driving this solution is the user experience. Anyone can get away with “forgetting” where a user was and simply redirecting to an entry point or login page upon receiving the ViewExpiredException. Though that’s easy to implement, it’s not exactly the most appealing functionality from the end user’s perspective. This solution tries to make your application as attractive as possible my minimizing the distractions. Even though it requires a little bit more work on the part of the developer, it goes a long way towards providing an intuitive experience to your users.

On the one hand, it’s a shame that the JSF spec didn’t have standard mechanisms for handling this extremely common use case. On the other hand, if it was the spec writers intention to keep us developers in business, they’ve done an excellent job. Time will tell whether JSF 2 will obviate the need for this custom solution.

Written by josephmarques

February 5, 2009 at 1:29 pm

Posted in webdev

Tagged with

HTML Odyssey – Form Submissions

with one comment

When developing any sufficiently complex web application, there will come a time when you need to support forms that have multiple submit buttons that do different things.  In the case of the RHQ platform, this is unavoidable.  In order to deal with the massive amounts of data RHQ is managing, many of the views are structured as tables where you can select one or many rows and simultaneously perform actions against them.

By default, the first button in the form is the handler for the enter key (as opposed to the act of explicitly clicking on some button to execute a specific action).  While it may seem like we’re picking nits here, having support for resetting what the “default button” is within your form actually goes a long way towards the intuitiveness of your application.  This is evidenced by the fact that JBoss Seam has a standard tag for this:

<s:defaultAction />

Unfortunately, however, this does not work generically across the board.  Since the JSF component developer has quite a bit of freedom in terms of how he/she can write the component implementation, I surmise that JBoss Seam needed to limit its support to a subset of components (perhaps even within a specific version range) to ensure compatibility and proper functioning.  The Seam JSF controls documentation confirms as much…but I’ll discuss more on that later.

I have to admit, I did think of using a javascript-based solution at first, but after giving it some thought I decided it was unnecessarily complicated for the task at hand.  I would have had to capture the enter key event at a global level and click the proper button to simulate a default action, not to mention dealing with potential differences across various browsers RHQ needs to support (for instance, do I add a listener to the window object or to document object?)

I ended up going with a solution that, believe it or not, actually exploits the problem to produce rather serendipitous results.  Since we already know that the first button in the form is the one that will get the enter key event we can – at the top of the form -try to “mimic” the button we want to be the default.

Truth be told, the solution was an adaption of something that Exuro posted on the forums.  His solution works at the pure HTML layer by adding:

<input type=”submit” value=”Submit I want to be default” name=”B2″/>

to the top of his form, and then wraps it in some kind of div that is either hidden, or taken out of the page flow and positioned off screen (thus making it effectively hidden).  However, since RHQ is deeply engrossed in JSF-land, the solution needed a slight tweak.  I couldn’t use a simple input control with a name attribute because the existing JSF navigation rules expect an outcome (a String return value), which in this case requires a method binding be present.  Luckily, Exuro’s solution translated nicely up to the JSF layer:

<h:commandButton name=”B2″ value=”#{someBean.someValue}” action=”#{someOtherBean.someAction}” />

As all JSF developers will know this tag eventually renders down into a simple input control whose type attribute is “submit” anyway.  So the rendered solution is nearly identical to the solution on the forum…except that it now properly honors the JSF-specific value and action attributes.

OK, so it may not be as pretty as dropping <s:defaultAction> as a child tag of the button that I want to be the default, but there seem to be no restrictions on this solution.  It works cross-browser and it works for any type of control that eventually renders to a button.

Although the Seam documentation says “Currently you can only nest [the defaultAction tag] inside buttons (e.g. <h:commandButton />, <a:commandButton /> or <tr:commandButton />). ” it seems to be slightly more restrictive than meets the eye.  The RHQ project has one component that extends the standard JSF command button to provide enhanced interaction between a button and the tabular results the button is performing actions against.  I tried the Seam solution against that custom component as follows:

<onc:selectCommandButton name=”B2″ action=”#{someBean.someAction}” value=”I should be the default now”  … >
<s:defaultAction />

Alas, it did not work.  Granted, I did confirm that the defaultAction tag work for h:commandButton and a:commandButton, but it does not seem to respect extensions for either of those components.  That’s what necessitated me to find an alternate solution. And that’s why the blog entry you just finished reading exists.

Written by josephmarques

January 28, 2009 at 10:39 am

Posted in webdev

Tagged with