How to create a New Custom JSF Component that randomly displays select items in SelectOne… and SelectMany components

1

Selection components, such as Radio Buttons. Dropdown-lists, Lists, Shuttles  and Check Boxes, are key elements of many a web page. Java Server Faces has a pretty wide range of such selection widgets available, from selectOneRadio to selectManyCheckbox in the RI and a wide range of additional components in distributions such as ADF Faces and MyFaces. The options to choose from are specified through SelectItem and SelectItems elements. For example:

&lt;h:selectOneRadio id=&quot;colorchooser&quot; layout=&quot;pageDirection&quot;&gt;<br />  &lt;f:selectItem itemLabel=&quot;Brown&quot; itemValue=&quot;Brown&quot;/&gt;<br />  &lt;f:selectItem itemLabel=&quot;Red&quot; itemValue=&quot;Red&quot;/&gt;<br />  &lt;f:selectItem itemLabel=&quot;Blue&quot; itemValue=&quot;Blue&quot;/&gt;<br />  &lt;f:selectItem itemLabel=&quot;Yellow&quot; itemValue=&quot;Yellow&quot;/&gt;<br />  &lt;f:selectItem itemLabel=&quot;Green&quot; itemValue=&quot;Green&quot;/&gt;          <br />&lt;/h:selectOneRadio&gt;<br />          &nbsp;<br />

The options are presented to the user in the order in which they are defined in the SelectItem and SelectItems elements. In most situations that is perfectly alright or even very desirable. However, there are situations where we might prefer to apply a random ordering to the options in the selection component. For example in Polls we would either not want to influence the poll result through presenting options in a specific order to every interviewee. And in Exams/tests we might want to minimize the risk of candidates informing each other on the correct answers by presenting the answers in an ever changing sequence.

The challenge I will face in this article is the implementation of a new JSF Component that will reshuffle the order of the select items. All we need to do in order to  make a  Select Component display its options in a random sequence is apply this new component.....

When I first started thinking about the implementation of randomly organized dropdown-lists and radio buttons, I considered at least four options for making the approach:

  1. randomize at the model level – at the source of the select items (provided of course the selectItems elements in powered by some backing bean)
  2. client-side randomize the rendered elements on load in the browser using JavaScript
  3. create my own components as alternative for the RI’s selectOneRadio, selectOneMenu, selectManyCheckbox etc.
  4. create a new component that can wrap the selection components such as selectOneRadio and somehow mess up there children
  5. create a new component that can wrap the selectItem and selectItems child elements of the selection components like selectOneRadio, selectManyList etc.

The first option was way too intrusive, could not distinguish between randomizing per session and per request, would not be able to deal with select options derived from multiple collections (multiple selectItems), so I could quickly discard it. The second one is incredibly messy and still required some server side component as well. It too was rapidly abandoned. Creating alternatives to selectOneRadio etc. – the third option – is a possibility, but would be my last resort as clearly it involves an awful lot of work and duplication of existing code and functionality. The fourth option is perhaps feasible, but not in a very simple way. I could pass the child selection component my own writer to render to and then engineer the html written to that writer object before sending it to the ‘real’ response writer. Again, not an attractive approach.

Then the last option presented itself and appeared to be a quite elegant one: we create a component that can be used like a regular selectItems component on the one hand, and therefore can be enclosed inside any select component, while on the other hand it can envelope selectItem and selectItems elements, retrieve and combine all their selectItem and pass them through to the parent selection component in a randomized order. This new component can be used in a JSF page like this:

&lt;h:selectOneRadio id=&quot;colorchooser&quot; layout=&quot;pageDirection&quot;&gt;<br />  &lt;AMISJSF:randomizeSelectItems&gt;<br />    &lt;f:selectItem itemLabel=&quot;Blue&quot; itemValue=&quot;Blue&quot;/&gt;<br />    &lt;f:selectItem itemLabel=&quot;Yellow&quot; itemValue=&quot;Yellow&quot;/&gt;<br />    &lt;f:selectItem itemLabel=&quot;Green&quot; itemValue=&quot;Green&quot;/&gt;<br />  &lt;/AMISJSF:randomizeSelectItems&gt;<br />&lt;/h:selectOneRadio&gt;<br />          &nbsp;<br />

It is easy to use: simply inject it between the selection component and its selection items. It can be used with every selection component that uses selectItems:

&lt;h:selectManyCheckbox id=&quot;colorchooser&quot; layout=&quot;pageDirection&quot;&gt;<br />  &lt;AMISJSF:randomizeSelectItems&gt;<br />    &lt;f:selectItem itemLabel=&quot;Blue&quot; itemValue=&quot;Blue&quot;/&gt;<br />    &lt;f:selectItem itemLabel=&quot;Yellow&quot; itemValue=&quot;Yellow&quot;/&gt;<br />    &lt;f:selectItem itemLabel=&quot;Green&quot; itemValue=&quot;Green&quot;/&gt;<br />  &lt;/AMISJSF:randomizeSelectItems&gt;<br />&lt;/h:selectManyCheckbox&gt; <br />

And with each render-operation, it will reshuffle the selection options. Note that we can have a combination of randomly shuffled elements and select items in a fixed order:

&lt;h:selectManyCheckbox id=&quot;colorchooser&quot; layout=&quot;pageDirection&quot;&gt;<br />  &lt;f:selectItem itemLabel=&quot;Brown&quot; itemValue=&quot;Brown&quot;/&gt;<br />  &lt;f:selectItem itemLabel=&quot;Red&quot; itemValue=&quot;Red&quot;/&gt;<br />  &lt;AMISJSF:randomizeSelectItems&gt;<br />    &lt;f:selectItem itemLabel=&quot;Blue&quot; itemValue=&quot;Blue&quot;/&gt;<br />    &lt;f:selectItem itemLabel=&quot;Yellow&quot; itemValue=&quot;Yellow&quot;/&gt;<br />    &lt;f:selectItem itemLabel=&quot;Green&quot; itemValue=&quot;Green&quot;/&gt;<br />  &lt;/AMISJSF:randomizeSelectItems&gt;<br />&lt;/h:selectManyCheckbox&gt; <br />

 

We can also use the randomizeSelectItems element with the ADF Model. See for example this snippet that renders a dropdown list of employees in a random order:

&lt;af:selectOneChoice &gt;<br />  &lt;AMISJSF:randomizeSelectItems&gt;<br />    &lt;f:selectItems value=&quot;#{bindings.EmpView1Ename.items}&quot;/&gt;<br />  &lt;/AMISJSF:randomizeSelectItems&gt;<br />&lt;/af:selectOneChoice&gt;<br /><br />

after refresh

Let’s take a look at the implementation of this new component.

The class implementing the RandomizeSelectItems component extends the UISelectItems class in the javax.faces.component package. Its getValue() method returns a Collection of selectItems. The class gets hold of the child selectItem and selectItems elements through the this.getChildren() call. It builds a list of all selectItems, using the helper class SelectItemSupport. Note that this is a class in the ADF Faces library, so we have created a dependency there. Also note that we could easily implement the functionality of SelectItemSupport ourselves. After building the entire collection, we apply the simplest way of randomizing the order of the collection’s elements: by using the Collections.shuffle() method.

package nl.amis.jsf;<br /><br />import java.util.ArrayList;<br />import java.util.Collections;<br />import java.util.List;<br /><br />import javax.faces.component.UISelectItem;<br />import javax.faces.component.UISelectItems;<br />import javax.faces.context.FacesContext;<br />import javax.faces.model.SelectItem;<br /><br />import oracle.adfinternal.view.faces.renderkit.uix.SelectItemSupport;<br /><br />/**<br /> * Class has to extend UISelectItems as supporting classes (such as javax.faces.component.SelectItemsIterator, SelectItemSupport)<br /> * used by UISelectOne and other selection components check explicitly for children<br /> * that are an instance of that class (if(kid instanceof UISelectItems)...)<br /> *<br /> */<br />public class RandomizeSelectItems extends UISelectItems {<br />    public RandomizeSelectItems() {<br />        setRendererType(null);<br />    }<br /><br />    public String getFamily() {<br />        return COMPONENT_FAMILY;<br />    }<br /><br />    public Object getValue() {<br />        List kids = this.getChildren();<br />        int childCount = this.getChildCount();<br />        List&lt;SelectItem&gt; siList = new ArrayList();<br />        for (int i = 0; i &lt; childCount; i++) {<br />            if (kids.get(i) instanceof UISelectItem) {<br />                SelectItemSupport.addSelectItem((UISelectItem)kids.get(i), <br />                                                siList);<br />            } else if (kids.get(i) instanceof UISelectItems) {<br />                SelectItemSupport.addSelectItems((UISelectItems)kids.get(i), <br />                                                 siList);<br />            }<br />        }<br />        Collections.shuffle(siList);<br />        return siList;<br />    }<br /><br />    public static final String COMPONENT_TYPE = &quot;RandomizeSelectItems&quot;;<br />    public static final String COMPONENT_FAMILY = &quot;javax.faces.SelectItems&quot;;<br /><br />}<br />&nbsp;

Other steps in implementing my new JSF Component:

  1. implement Tag Class
  2. add description to TLD
  3. register component in faces-config
  4. package and distribute
  5. use in new JSF applications

1. Implement Tag Class

A very simple class, as this tag has not attributes:

package nl.amis.jsf.tags;<br /><br />import javax.faces.application.Application;<br />import javax.faces.component.UIComponent;<br />import javax.faces.context.FacesContext;<br />import javax.faces.el.ValueBinding;<br />import javax.faces.webapp.UIComponentTag;<br /><br />public class RandomizeSelectItemsTag extends UIComponentTag {<br /><br />    public RandomizeSelectItemsTag() {<br />    }<br /><br />    protected void setProperties(UIComponent component) {<br />        super.setProperties(component);<br />    }<br /><br />    public void release() {<br />        super.release();<br />    }<br /><br /><br />    public String getComponentType() {<br />        return &quot;RandomizeSelectItems&quot;;<br />    }<br /><br />    public String getRendererType() {<br />        return null;<br />    }<br />}<br />&nbsp;

2. Add description to Tag Library Description

  &lt;tag&gt;<br />    &lt;description&gt;Randomize the order of display of the enclosed select items&lt;/description&gt;<br />    &lt;display-name&gt;Randomize Select Items&lt;/display-name&gt;<br />    &lt;name&gt;randomizeSelectItems&lt;/name&gt;<br />    &lt;tag-class&gt;nl.amis.jsf.tags.RandomizeSelectItemsTag&lt;/tag-class&gt;<br />    &lt;body-content&gt;JSP&lt;/body-content&gt;<br />    &lt;example&gt;Brief snippet showing how to use this tag.&lt;/example&gt;<br />  &lt;/tag&gt; <br />

3. Register component in faces-config

  &lt;component&gt;<br />    &lt;component-type&gt;RandomizeSelectItems&lt;/component-type&gt;<br />    &lt;component-class&gt;nl.amis.jsf.RandomizeSelectItems&lt;/component-class&gt;<br />  &lt;/component&gt;<br />&nbsp;

4. Package and Distribute

See  previous article on Deploying, Packaging and Distributing Custom JSF Components for details.

5. Use the new Custom JSF Component in JSF Applications

Also see the article referenced above. And see the snippets at the start of this article. Note that any combination of SelectItem and SelectItems can be nested inside a randomizeSelectItems tag. That tag itself is treated as if it were a SelectItems tag by its parent.

Further Steps

While we may want to present the select-options in random order to each new interviewee, candidate or contestant, we probably want to present them in the same order for every new display in the same session for the same user. So we should add to the new component a way of having it randomize for every request or for every session.

Resources

Accessible and pretty complete Tutorial on creating new JSF component  http://www.exadel.com/tutorial/jsf/HowToWriteYourOwnJSFComponents.pdf  

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

1 Comment

  1. How can i know to add a custom tag ..Not custom component….
    I need to ontroduce fieldest tag along with legend in JSF without using any other jars.