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.

6 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes