Monday, November 25, 2013

JSF 2 Custom Scopes without 3rd party libraries

Almost every JSF application that I am aware of uses some mechanism to store values in a scope longer than the original “Request Scope” but shorter than “Session Scope”. “Wizards” are a common scenario. Unfortunately, JSF comes without something like a conversation scope, but there are some frameworks that offer this functionality:
  • MyFaces Orchestra
  • Seam
  • Spring
  • CDI
So, while technical solutions exist, they require integration of at least one 3rd party library. Not a big deal in a newly created project, but it can become a serious problem with existing code or legacy applications.
JSF 2.2 addresses this problem with a cool new feature: “Flow scopes” (See this excellent post about whats hot in JSF 2.2). While it might be a nice solution, it is still unclear to me if “Flow Scopes” will work without CDI. Besides this, JSF 2.2 Flows seem to require a lot of configuration so it might be somewhat oversized and less suitable in some scenarios.
Though JSF lacks a “conversation scope” and JSF 2.2 is still not yet available, there is already a JSF 2.0 feature that seems to be mostly unknown to a lot of JSF developers: JSF “Custom Scopes”.
Custom scopes were anounced as a major feature for JSF 2 (see this blogpost from Andy Schwartz) but for some reason it must have fallen from grace: The final release of the JSF 2 specification remains silent on custom scopes, though the API includes the necessary annotation and events .
While I think custom scopes are an enormous useful feature, there are very few resources dealing with it. There is an older blog post from Ryan Lubkewhich uses an outdatet API (early draft I guess).
So, if f you need a custom scope, here is how to create one:
First of all, we need a class that will represent our custom scope. This class will be responsible for storing named objects. Stored objects will be accessible using EL expressions. So, insted of putting our managed beans into request scope, we will be able to put them into our custom scope. The class therefore needs to implement the map interface:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class CustomScope extends ConcurrentHashMap {
 
    private static final long serialVersionUID = 6013804747421198557L;
 
    public static final String SCOPE_NAME = "CUSTOM_SCOPE";
 
    public CustomScope(){
        super();
    }
 
    public void notifyCreate(final FacesContext ctx) {
 
        ScopeContext context = new ScopeContext(SCOPE_NAME, this);
        ctx.getApplication().publishEvent(ctx, PostConstructCustomScopeEvent.class, context);
 
    }
 
    public void notifyDestroy(final FacesContext ctx) {
 
        ScopeContext scopeContext = new ScopeContext(SCOPE_NAME,this);
        ctx.getApplication().publishEvent(ctx, PreDestroyCustomScopeEvent.class, scopeContext);
 
    }
 
}
The scope itself needs to be held somewhere. For this example it will be put into session scope for the time needed. At a particular point in time we can discard the scope by removing it from session.
So, whats the point of having a custom scope when it will be stored in session anyway?
The scope can contain many beans that we would else have to put in (and remove from) the session manually. We can also remove them all at once by removing the scope object from session. This way, the risk to forget to clean things up is greatly reduced.
Defining beans to belong to our custom scope is not only convenient, it also enables us to have distinct scopes for different aspects of the application. All session data may be accessed concurrently (multiple browser windows). This is why the scope class needs to extend java.util.concurrent.ConcurrentHashMap. The class furthermore provides two methods to publish SystemEvents, so other components may be notified when the scope is created or destroyed.
This is how a managed bean can be attached to our custom scope:
1
2
3
4
5
6
7
@ManagedBean
@CustomScoped("#{customScope}")
public class ExampleBean implements Serializable {
 
...
 
}
As you can see, the name of the scope has to be defined in the annotations EL expression.
For JSF to be able to resolve the EL expression, we need to define a custom ELResolver. ELResolvers do axactly that: They try to resolve EL expressions. You can have any number of ELResolvers in your application. They are chained together in the order of their occurence in the faces-config.xml. This is the code for the ELResolver for our custom scope:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class CustomScopeELResolver extends ELResolver {
 
    @Override
    public Object getValue(final ELContext elContext,
        final Object base,
        final Object property) {
 
        if (property == null) {
            throw new PropertyNotFoundException();
        }
 
        FacesContext facesContext = (FacesContext) elContext.getContext(FacesContext.class);
 
        if ((null == base) && CustomScope.SCOPE_NAME.equals(property.toString())) {
 
            // Scope is referenced directly
 
            CustomScope scope = getScope(facesContext);
            elContext.setPropertyResolved(true);
            return scope;
 
        } else if ((null != base) && (base instanceof CustomScope)) {
 
            // An object within the scope is referenced
 
            return resolve(facesContext, (CustomScope) base, property.toString());
 
        } else if (null == base) {
            CustomScope customScope = getScope(facesContext);
            return null != customScope ?
                resolve(facesContext, customScope, property.toString()):null;
 
        }
        return null;
    }
 
    /**
     * Resolve the key on the given CustomScope
     */
    public Object resolve(final FacesContext facesContext,
        final CustomScope scope,
        final String key) {
 
        Object value = scope.get(key);
        facesContext.getELContext().setPropertyResolved(value != null);
        return value;
 
    }
 
 
    /**
     * Responsible to retrieve the scope
     */
    private CustomScope getScope(final FacesContext facesContext) {
 
        Map sessionMap = facesContext.getExternalContext().getSessionMap();
        CustomScope customScope = (CustomScope) sessionMap.get(CustomScope.SCOPE_NAME);
 
        return customScope;
    }
...
}
The ELResolver needs to be defined in faces-config.xml:
1
2
3
4
5
6
7
8
xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
 <application>
  <el-resolver>de.thomasasel.jsf.example.CustomScopeELResolver</el-resolver>
 </application>
</faces-config>
The getValue-Method will be called once an ELExpression needs to be resolved. The resolver will return null if the expression cannot be resolved.
In this case the next resolver in the chain will be called and so on until the expression is either finally resolved or the last ELResolver returns null.
By now we have a managed bean that is tied to the custom scope. Thanks to our custom EL resolver we can access the bean and its properties from markup using EL:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
 
<h:head>
    <title>Custom Scope example</title>
</h:head>
<h:body>
    <h:form>
        <h:inputText value="#{exampleBean.text1}"/>
    </h:form>
</h:body>
</html>
As you can see, the bean is referenced by name as it would be the case with any other scope.
Finally we need to control the lifecycle of the scope. When will it be created? When is it destroyed?
I decided to use ActionListeners for this task. The listeners will put the custom scope in the session and remove it from there. They will also notify other components by calling the scopes notifyCreate and notifyDestroy methods:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class CreateCustomScope implements ActionListener {
 
    @Override
    public void processAction(final ActionEvent event) throws AbortProcessingException {
 
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Map sessionMap = facesContext.getExternalContext().getSessionMap();
 
        CustomScope customScope = new CustomScope();
        sessionMap.put(CustomScope.SCOPE_NAME, customScope);
 
        customScope.notifyCreate(facesContext);
 
    }
 
}
 
public class DestroyCustomScope implements ActionListener {
 
    @Override
    public void processAction(final ActionEvent event) throws AbortProcessingException {
 
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Map sessionMap = facesContext.getExternalContext().getSessionMap();
 
        CustomScope customScope = (CustomScope) sessionMap.get(CustomScope.SCOPE_NAME);
        customScope.notifyDestroy(facesContext);
 
        sessionMap.remove(CustomScope.SCOPE_NAME);
 
    }
 
}
Both listeners are attached to some navigations buttons, so the lifecycle of the scope depends on the users navigation path.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
 
<h:head>
    <title>Custom Scope example</title>
</h:head>
 
<h:body>
    <h:form>
 
        <h:commandButton value="start" action="page1.xhtml">
            <f:actionListener type="de.thomasasel.jsf.example.CreateCustomScope" />
        </h:commandButton>
 
    </h:form>
 
</h:body>
</html>
ActionListeners were chosen just for the sake of simplicity for this example. A custom NavigationHandler using JSFs ConfigurableNavigationHandler API is a way more flexible and clean solution as it keeps the aspect of lifecycle control out of the view declaration.
Thats it. Nothing left to do but to play around with this cool feature. You can get the sourcecode for this example from GitHub
If anybody has information about why CustomScopes are not mentioned with a single word in the spec, please drop me a line.

No comments: