Jim Driscoll's Blog

Notes on Technology and the Web

Archive for the ‘JSF’ Category

Bridging to Open Ajax

leave a comment »

The Open Ajax Alliance is a standards organization with the mission of ensuring interoperability within Web based Ajaxified applications. One of their standards relates to intercomponent communication – the ability to subscribe and publish messages which can then be picked up by code written by other authors.

Please note that if you don’t have an interest in Open Ajax, this post may not be especially illuminating – I’ve talked about the addOnEvent function before, even recently.

To write an Open Ajax application, you need to subscribe to events, much like in JSF 2, by registering functions which act as listeners. For instance, suppose we had a field in our page that looked like this:

 <textarea id="statusArea" cols="40" rows="10" readonly="readonly" />

And we wanted to use this textarea to write out certain events that we’d like to track. I could then have this code in a JavaScript file:

   1 var statusUpdate = function statusUpdate(name, data) {
   2     var statusArea = document.getElementById("statusArea");
   3     var text = statusArea.value;
   4     text = text + "Name: "+data.source.id;
   5     if (name === "jsf.event") {
   6         text = text +" Event: "+data.status+"\n";
   7     } else if (name === "jsf.error") {  
   8         text = text + " Error: "+data.status+"\n";
   9     }
  10     statusArea.value = text;
  11 };
  12 
  13 OpenAjax.hub.subscribe("jsf.event",statusUpdate);
  14 OpenAjax.hub.subscribe("jsf.error",statusUpdate);

In this case, we’re subscribing to two channels – jsf.event and jsf.error, and calling the statusUpdate function when a message arrives on those channels.

So, where do those messages come from? Unlike JSF, the OpenAjax hub has a publish function, in addition to a subscribe function. By associating that publish function with a call to jsf.ajax.addOnEvent and jsf.ajax.addOnError, we can bridge between the two event systems – like this:

   1 var openajaxbridge = {};
   2 
   3 openajaxbridge.eventUpdate = function eventUpdate(data) {
   4     OpenAjax.hub.publish("jsf.event", data);
   5 };
   6 
   7 openajaxbridge.errorUpdate = function errorUpdate(data) {
   8     OpenAjax.hub.publish("jsf.error",data);
   9 };
  10 
  11 jsf.ajax.addOnEvent(openajaxbridge.eventUpdate);
  12 jsf.ajax.addOnError(openajaxbridge.errorUpdate);

As I said, this is a somewhat specialized topic, but I thought it worth mentioning. The full code of the demo, including putting it into a component, is in Project Mojarra’s source base, under the jsf-demo/OpenAjaxBridge directory.

(This article originally published on my java.net blog on September 3, 2009.)

Written by Jim Driscoll

February 9, 2010 at 10:08 PM

Posted in ajax, JSF

Busy status indicator with JSF 2

leave a comment »

I’ve had a few requests on how to write a busy status indicator – you know, the little spinning ball that’s there while an Ajax call is active, and which goes away once the request is complete. So, I spent about two hours today, and did just that – including putting it into a component so it’s reusable. As usual, it involved no Java, and only a minimal amount of JavaScript.

First, I needed an animated gif for a spinning image – there were a number at http://mentalized.net/activity-indicators – I just picked one. They’re all in the public domain, and there are other sites which offer similar animated gif spinners.

After that, I tried to imagine what it would look like in the using page. Something like this seemed appropriate:

   1 <html xmlns="http://www.w3.org/1999/xhtml"
   2       xmlns:ui="http://java.sun.com/jsf/facelets"
   3       xmlns:h="http://java.sun.com/jsf/html"
   4       xmlns:f="http://java.sun.com/jsf/core"
   5       xmlns:ez="http://java.sun.com/jsf/composite/busystatus">
   6 <h:head>
   7     <title>Busy Busy</title>
   8 </h:head>
   9 <h:body>
  10     <h:form id="busyForm">
  11         <h:inputText id="in" value="#{string.string}">
  12             <f:ajax render="out"/>
  13         </h:inputText><ez:busystatus id="busy" for="busyForm:in" /><br/>
  14         <h:outputText id="out" value="#{string.string}"/><br/>
  15         <h:commandButton type="button" value="Click Me"/>
  16     </h:form>
  17 </h:body>
  18 </html>

On line 13, you see a component, busystatus, with a single attribute, “for”, which is pointing at the rendered ID of the component I want to monitor. Otherwise, it’s a straightforward JSF Ajax app – Ajaxify the “in” component, write to the the “out” component. I had to use the rendered ID (busyForm:in) rather than the JSF id (in), because there was no easy way to do ID resolution inside the component, but we’ve had to deal with that often enough at this point that the difference shouldn’t be too confusing.

We’ll also have make sure that the Ajax request lasts long enough to visibly trigger the indicator – that’s as simple as adding a Thread.sleep(2000); to the setString method of the bean referenced by #{string}.

With that out of the way, let’s write the component. Here’s the composite component implementation section (the interface section just refers to the “for” attribute, so there’s nothing to see there):

   1 <h:outputScript name="jsf.js" library="javax.faces" target="head"/>
   2 <h:outputScript name="busystatus/busystatus.js" target="head"/>
   3 <script type="text/javascript">
   4     busystatusdemo.init("#{cc.clientId}", "#{cc.attrs.for}");
   5 </script>
   6 <span id="#{cc.clientId}" style="display:none;">
   7    <h:graphicImage id="busyindicator" height="15" width="15" name="busystatus/spinner3-greenie.gif"/>
   8 </span>

Line 1 loads the jsf.js library, if necessary. We’ll need it in the next file for listening to events – note that it’ll get loaded anyway, from any f:ajax tag we use, but it’s good practice to make sure that it’s loaded before we try to reference it. Line 2 will load the JavaScript we’ve written for this component. We could have just put the script inline in the composite component itself, but then we’d bloat the size of the page unnecessarily if we used this component more than once in the page. What works best for performance is going to vary on case by case basis, but since we’re trying to create a generally reusable component, this is probably the best way to do it. Lines 3 thru 5 call the init function for this component, which we’ll use to associate the component ID with the for attribute: this is the same trick we use for almost every Ajax component on this blog, so again, this shouldn’t be surprising.
Lines 6 thru 8 define a span wrapping an image. The span is initially set to be invisible with a style attribute, and we’ll make it visible via JavaScript calls once the ajax request is active. The image itself is loading the spinning animated gif as a resource – and it’s in the same resource library as the component itself.

So, to recap what’s happening in this file: We load the required scripts, run an initialization function, and set up an invisible span holding the image we’ll display later. Now, let’s examine the last file for this component, the busystatus.js file that holds the functions that’ll be doing all the work on the page:

   1 if (!window["busystatusdemo"]) {
   2     var busystatusdemo = {};
   3 }
   4 busystatusdemo.onStatusChange = function onStatusChange(data) {
   5     var status = data.status;
   6     var componentID = busystatusdemo[data.source.id];
   7     if (!componentID) {  // if there's no request to listen for this one component, then leave
   8         return;
   9     }
  10     var element = document.getElementById(componentID);
  11     if (status === "begin") { // turn on busy indicator
  12         element.style.display = "inline";
  13     } else {  // turn off busy indicator, on either "complete" or "success"
  14         element.style.display = "none";
  15     }
  16 };
  17 
  18 jsf.ajax.addOnEvent(busystatusdemo.onStatusChange);
  19 
  20 busystatusdemo.init =  function init(componentID, forValue) {
  21     busystatusdemo[forValue] = componentID;
  22 };

Three sections here: Lines 1 thru 3 set up the namespace. Lines 20 thru 22 are the initialization function that creates a map between the component and the for attribute. Let’s go over lines 4 thru 18, though, since that’s doing the interesting bit…

On line 18, we’re adding an event listener – after this call, whenever an event occurs, the onStatusChange function will be called with a single parameter. When that function is called, on lines 6 thru 10, we retrieve the id of the component that generated the event, and use it to look up the associated “for” value, and exit the function if there’s no associated “for” value. Then, lines 11 thru 15, we check whether we’re beginning the Ajax call, or ending it. If beginning, we display the gif – if ending, we hide the gif.

So, that’s our very simple busy component. But please note that this isn’t really done. For instance, by revealing and hiding the gif, we’re actually altering the layout of the page – there’s traditionally two different ways to deal with this: you can either swap between the animated gif and a blank, transparent gif of the same size, or use CSS to hardcode in the size of a span, which wraps the component that’s having it’s display set to none. Either would work, and both are really out of scope for this blog – my only goal for this blog was to just show you how to use the event to trigger changes that updated a status indicator.

As usual, you can find the code for this blog in the Project Mojarra codebase, under the jsf-demo/ajax-components directory.

Questions? Please ask in the comments section, and I’ll do my best to answer them.

UPDATE: Ed Burns, in the comments, recommends http://www.ajaxload.info as a great place for all your spinning gif needs.

(This article originally published on my java.net blog on September 2, 2009.)

Written by Jim Driscoll

February 9, 2010 at 10:07 PM

Posted in ajax, JSF

Inline Scripts with Mojarra

leave a comment »

A few weeks ago, I blogged about ways to execute scripts on the client which you were writing out from the server via Ajax.  By popular demand, the latest build of Mojarra now allows execution of inline scripts.

So, instead of having to either bundle code into an <eval> tag, or using an event to execute it later, you can now simply say something like:

<script type="text/javascript">alert("Hello there");</script>

right inside the rendered html.

You can also say something like:

<script type="text/javascript" src="file.js"></script>

And the script will be loaded as well.

This feature will (probably) be the next revision of the specification, but you should be able to use this feature without fear of compatability issues going forward – the specifcation’s Expert Group has already expressed their approval of including this.

(This article originally published on my java.net blog on September 2, 2009.)

Written by Jim Driscoll

February 9, 2010 at 10:05 PM

Posted in ajax, JSF

ui:repeat and Ajax

with one comment

A nice feature of Facelets is the ui:repeat tag, which iterates over a supplied list of values to do a full list on your page. One problem: it’ll add an index to the generated id’s, which can make using it with Ajax a bit of a drag. But if you’re just using the f:ajax tag, that index is detected automatically, making ajaxifying the tag relatively easy. Here’s a quick example:


Say you want to make a page that offers three drop down menus with three choices each (it’s a simple example, work with me here). Here’s the data structure, set up as a bean:

   1 package demo;
   2 
   3 import java.util.ArrayList;
   4 import java.util.Arrays;
   5 import java.util.List;
   6 import javax.faces.bean.ManagedBean;
   7 
   8 @ManagedBean
   9 public class RepeatBean {
  10 
  11     private String[] sarray = {"one", "two", "three"};
  12     private String[] sarray2 = {"four", "five", "six"};
  13     private String[] sarray3 = {"seven", "eight", "nine"};
  14 
  15     private List<List<String>> llist;
  16 
  17     private String[] resultArray = {"two", "four", "nine"};
  18 
  19     public RepeatBean() {
  20         List<String> slist = Arrays.asList(sarray);
  21         List<String> slist2 = Arrays.asList(sarray2);
  22         List<String> slist3 = Arrays.asList(sarray3);
  23 
  24         llist = new ArrayList<List<String>>();
  25         llist.add(slist);
  26         llist.add(slist2);
  27         llist.add(slist3);
  28 
  29     }
  30     public List<List<String>> getLlist() {
  31         return llist;
  32     }
  33     public String[] getResultArray() {
  34         return resultArray;
  35     }
  36     public String getResultArray(int i) {
  37         return resultArray[i];
  38     }
  39     public void setResultArray(int i, String value) {
  40         resultArray[i] = value;
  41     }
  42     public void setResultArray(String[] resultArray) {
  43         this.resultArray = resultArray;
  44     }
  45 }


We create three lists – they’ll be the content of the drop down menus. We then create a list of String lists – llist – we’ll use this as the input for the . We also make a list to hold the results: resultArray.

Now: to use it in a page:

   1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   2 <html xmlns="http://www.w3.org/1999/xhtml"
   3       xmlns:ui="http://java.sun.com/jsf/facelets"
   4       xmlns:h="http://java.sun.com/jsf/html"
   5       xmlns:f="http://java.sun.com/jsf/core"
   6       xmlns:c="http://java.sun.com/jsp/jstl/core">
   7     <h:head>
   8         <title>Repeat Test Demo</title>
   9     </h:head>
  10     <h:body>
  11 
  12         <h:form id="repeatForm">
  13             <ui:repeat value="#{repeatBean.llist}" var="list" varStatus="current" id="repeat">
  14                 <h:selectOneMenu value="#{repeatBean.resultArray[current.index]}" id="chooseOne">
  15                     <f:selectItems value="#{list}"/>
  16                     <f:ajax render="outText"/>
  17                 </h:selectOneMenu>
  18                 <h:outputText value="#{repeatBean.resultArray[current.index]}" id="outText"/>
  19                 <br/>
  20             </ui:repeat>
  21         </h:form>
  22     </h:body>
  23 </html>


This ends up generating ids for the outputText field that look like: repeatForm:repeat:2:outText. But because we’re using the f:ajax tag, we only need to specify “outText” – the tag takes care of the work of finding out what the real id is.


Neat, huh? In case you’re not familiar with the ui:repeat tag – you should take a minute to get familiar with it, it’s core Facelets functionality. By using the var value, we’re saying that we want to create a list variable that will contain one of the lists in llist every iteration. By using varStatus and the index property, we’re keeping track of all of the values selected.


Just a simple example of the use of the f:ajax tag in a complex rendered environment. As always, let me know if you have any questions.

(This article originally published on my java.net blog on August 17, 2009.)

Written by Jim Driscoll

February 9, 2010 at 10:03 PM

Posted in ajax, JSF

Keeping focus

leave a comment »


A recent user question, which has been repeated enough times to warrant a blog posting. In short: Why am I losing focus when I use the <f:ajax> tag?


Let’s imagine you have a form, with two input fields and two output fields:

   1 <h:form>
   2 <f:ajax event="blur" render="@form">
   3   <h:inputText id="onein" value="#{bean.one}">
   4   </h:inputText>
   5   <h:outputText id="oneout" value="#{bean.one}" />
   6   <h:inputText id="twoin" value="#{bean.two}">
   7   </h:inputText>
   8   <h:outputText id="twoout" value="#{bean.two}" />
   9 </f:ajax>
  10 <h:commandButton value="Submit" />
  11 </h:form>

You enter data in field one, tab to field two, and bam! the focus on field two is lost.


Why?


When you tabbed out of field one, you generated a blur event. This calls an Ajax request, which updates the entire form. That, in turn, removes and re-adds all of the elements in that form – including field 2. With that field (momentarily) gone, the focus is lost.


So, how to deal with this?


Simple rule: Don’t replace the parent element of the element whose focus you want to keep. There’s also a simple corollary: Don’t update stuff you don’t have to.


Here’s the changed markup that works:

   1 <h:form>
   2   <h:inputText id="onein" value="#{bean.one}">
   3     <f:ajax render="oneout"/>
   4   </h:inputText>
   5   <h:outputText id="oneout" value="#{bean.one}" />
   6   <h:inputText id="twoin" value="#{bean.two}">
   7     <f:ajax render="twoout"/>
   8   </h:inputText>
   9   <h:outputText id="twoout" value="#{bean.two}" />
  10 <h:commandButton value="Submit" />
  11 </h:form>


Note that you could also say render=”onein oneout twoout twoin” and it will still work because you aren’t updating the parent (the h:form) – even though you’re updating the field that has the focus.

Questions? Ask below.

(This article originally published on my java.net blog on August 11, 2009.)

Written by Jim Driscoll

February 9, 2010 at 10:03 PM

Posted in ajax, JSF

Making a YUI Calendar Component in JSF2

leave a comment »


In my last blog entry, I went over getting a YUI widget working on JSF2. This time, let’s go over what’s required to move that widget into a JSF component. No Java required, but a fair bit of JavaScript.


In a lot of ways, this is just like other components that I’ve written about. The tricks are much the same – saving values into a JavaScript context. Including scripts into the component, that sort of thing.


Let’s go over the component, one file at a time. First, the using page:


   1    <ez:yuical id="cal1" value="#{date.date1}" render="out1"/>
   2    <h:outputText id="out1" value="#{date.date1}">
   3        <f:convertDateTime pattern="MM/dd/yyyy"/>
   4    </h:outputText>



To use the component, we just pass it two attributes – value, which is a managed property of type Date, and an optional render attribute, which will be updated via an ajax call when we click on a date in the component.


Simple enough. But since we’re using the version of the YUI code that’s served from Google, we’ll have to include the code in the head.



<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/yuiloader/yuiloader.js"></script&gt;


Why? Because JSF’s resource API assumes all resources are local – meaning that you can’t use the h:outputScript and h:outputStylesheet with resources external to your server. I thought about showing this example with locally available resources (it’s cleaner, of course), but thought the point was worth making. Hopefully, the 2.1 version of JSF will have the ability to specify a URL, in addition to just a local resource name.


So, that’s the using page: what’s the component look like? Not much, it turns out:

   1    <composite:interface name="yuical"
   2                         displayName="YUI Cal Component"
   3                         shortDescription="YUI Calendar Component">
   4        <composite:attribute name="value" required="true" type="java.util.Date"/>
   5        <composite:attribute name="render" required="false" type="java.lang.String"/>
   6    </composite:interface>
   7    
   8    <composite:implementation>
   9        <h:outputScript name="jsf.js" library="javax.faces" target="head" />
  10        <h:outputScript name="yuical/calendar.js" target="head" />
  11    
  12        <h:panelGrid class="yui-skin-sam" id="holdingContainer">
  13            <h:panelGroup layout="block" id="calContainer"/>
  14            <h:inputHidden id="date" value="#{cc.attrs.value}">
  15                <f:convertDateTime pattern="MM/dd/yyyy"/>
  16            </h:inputHidden>
  17        </h:panelGrid>
  18        <script type="text/javascript">
  19             demo.calendar.init("#{cc.clientId}", "#{cc.attrs.render}");
  20        </script>
  21    </composite:implementation>



The interface section (lines 1-6) just details what I’ve already gone over – two attributes, a value that’s a date, and required, and a value that’s a string, and that optionally points to an id that will be updated when the date value is selected.


Lines 9-10 are where we include the scripts for the component – and as I’ve previously mentioned, if we were to have the YUI JavaScripts locally, this is where we’d include those as well.


Lines 12-17 are the same as our previous blog, where we set up the necessary structure for the widget, as well as the hidden field which we’ll update when a date is selected in the widget.


Last, we have the script at line 19 – a simple call to init, passing in the contextual render value, so we can use more than one of these components in a page.


Now, let’s look at the JavaScript code. It’s long (for a simple demo), but much of it is the same as my previous blog, and quite a bit is simply necessary fluff. We’ll take it on in three chunks, corresponding to the three sections of the code – the setup, the init function, and the handler function.

   1    if (typeof demo == "undefined" && !demo) {
   2        var demo = {};
   3    }
   4    
   5    if (typeof demo.calendar == "undefined" && !demo.calendar) {
   6        demo.calendar = {};
   7    }
   8    
   9    if (typeof demo.calendar.contextMap === "undefined" && !demo.calendar.contextMap) {
  10        demo.calendar.contextMap = [];
  11    }



This is just a simple initialization of the objects we’ll be using the JavaScript. We escape it, so we don’t set them up twice – this lets us use more than one component in a page.


Now we’ll look at the init function that’s called within the component’s XHTML:

  13    demo.calendar.init = function init(context, render) {
  14    
  15        // record the render attribute, if applied
  16        demo.calendar.contextMap[context] = render;
  17    
  18        demo.calendar.loader = new YAHOO.util.YUILoader({
  19            base: "http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/",
  20            require: ["calendar"],
  21            loadOptional: false,
  22            combine: false,
  23            filter: "RAW",
  24            allowRollup: false,
  25            onSuccess: function() {
  26                try {
  27                    demo.calendar.cal1 = new YAHOO.widget.Calendar("demo.calendar.cal1", context+":calContainer");
  28                    demo.calendar.cal1.render();
  29                    demo.calendar.cal1.selectEvent.subscribe(demo.calendar.handleSelect, demo.calendar.cal1, true);
  30                } catch (e) {
  31                    alert(e);
  32                }
  33            },
  34            // should a failure occur, the onFailure function will be executed
  35            onFailure: function(o) {
  36                alert("error: " + YAHOO.lang.dump(o));
  37            }
  38    
  39        });
  40    
  41        //
  42        // Calculate the dependency and insert the required scripts and css resources
  43        // into the document
  44        demo.calendar.loader.insert();
  45    }



This code is almost the same as in the previous blog – naturally, since most of this is necessary for setting up the Calendar itself. Two changes, to let it be in a reusable component: line 16, which records the render attribute, and associates it with the component’s id value, and line 27, where we also take into account the component’s value.


And, finally, here’s the handler, which does most of the heavy (JSF specific) lifting for this component:

  48    demo.calendar.handleSelect = function handleSelect(type, args, obj) {
  49    
  50        if (type === "select") {
  51            var calId = obj.containerId;
  52            var index = calId.indexOf(":") + 1;
  53            var tmpindex = calId.substring(index).indexOf(":") + 1;
  54            // keep looking until you get the last child index
  55            while (tmpindex !== 0) {
  56                index += tmpindex;
  57                tmpindex = calId.substr(index).indexOf(":") + 1;
  58            }
  59            var containerId = calId.substring(0,index - 1);
  60            var dateId = containerId + ":" + "date";
  61            var dates = args[0];
  62            var date = dates[0];
  63            var year = date[0], month = date[1], day = date[2];
  64    
  65            var txtDate = document.getElementById(dateId);
  66            txtDate.value = month + "/" + day + "/" + year;
  67    
  68            var render = demo.calendar.contextMap[containerId];
  69            try {
  70                // if a render is defined for the component, then include it.
  71                if (typeof render !== "undefined" && render ) {
  72                    jsf.ajax.request(dateId,null,{
  73                        render: render,
  74                        execute: dateId
  75                    })
  76                } else {
  77                    jsf.ajax.request(dateId,null,{
  78                        execute: dateId
  79                    })
  80                }
  81            } catch (e) {
  82                alert(e);
  83            }
  84        }
  85    }



By using the passed in ID of the widget that was triggered, we obtain the id’s of the component, and from there the id of the date field (lines 51-60).


As in the previous blog, we then get the element that corresponds to the hidden field, and set it (lines 65-66).


Then retrieve the render value based on the component’s id. If there is a value (remember, it’s an optional value), use it, otherwise, don’t.


And finally, perform a jsf.ajax call with the hidden value as the executed portion – which will set it on the server.


And that’s it – we now have a component that graphically allows for selecting a date, and having it reflected on the server. Neat, huh?


Anyway, I’ll be uploading this into the Project Mojarra demo directory now that it’s complete, in the ajax-component demo. You can check out the full code there.


Feel free to ask questions, below.

(This article originally published on my java.net blog on August 9, 2009.)

Written by Jim Driscoll

February 9, 2010 at 9:58 PM

Posted in ajax, JSF, YUI

Using the YUI Calendar widget with JSF 2

leave a comment »

If you’re not developing JSF with third party component libraries, you’re really missing out on the best part of JSF. But there’s lots of Ajax widgets out there, which contain all kinds of useful functionality. Wouldn’t it be useful to use those within your JSF pages?


The Yahoo UI library is pretty nifty stuff, and the Calendar widget is useful, pretty, and powerful. Let’s wire it into a JSF page, and bind the return of that widget to the property of a bean. How hard could it be? 71 lines, of which about 45 or so are non-boilerplate. Let’s take a look. Here’s what the page is going to look like when we’re done:
Screen Shot


And, line by line, here’s the breakout of the code – note that for this example, I’ve placed everything in one file, but you’d really want to break things out for a production environment.


   1    <?xml version="1.0" encoding="UTF-8"?>
   2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   3    <html xmlns="http://www.w3.org/1999/xhtml"
   4          xmlns:h="http://java.sun.com/jsf/html"
   5          xmlns:f="http://java.sun.com/jsf/core"
   6          xmlns:ui="http://java.sun.com/jsf/facelets">
   7        <h:head>
   8            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/yuiloader/yuiloader.js"></script>
   9            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  10            <title>Test Binding</title>
  11        </h:head>
  12        <h:body>
  13            <h:outputScript name="jsf.js" library="javax.faces" target="head" />



The above code is mostly preamble, but there’s one necessary part worth exploring – Line 8 – we must use the script tag, rather than a h:outputScript tag, since outputScript is only for local resources, and this is calling an external URL. We’re using the Yahoo loader API, which we’ll call later on line 53 to load everything we need from yahoo. We’re loading this from Google’s website, primarily to keep everything in one file – whether to use local files or Google’s copies is an interesting question, but out of scope for this blog entry.

  14            <h:form id="form1" prependId="false">
  15                <div class="yui-skin-sam">
  16                    <div id="cal1Container"></div>
  17                </div>
  18                <h:inputHidden id="date" value="#{date.date}">
  19                    <f:convertDateTime pattern="MM/dd/yyyy"/>
  20                </h:inputHidden>
  21                <p>
  22                    The set date is:
  23                    <h:outputText id="out" value="#{date.date}" >
  24                        <f:convertDateTime/>
  25                    </h:outputText>
  26                </p>



Line 15-17 are the two divs that the YUI Calendar wants to see to set itself up. Note that we’re calling calendar div “cal1Container”. This will be the only part of our page that accepts input.


Line 18-20 is an h:inputHidden field that we’ll use to store the date entered into by the Calendar widget. We call it “date”, and we’ll reference it later on in the page.


Line 21-26 is our output mechanism for this page – strictly speaking, we don’t need this at all. After all, we’re already displaying the value of the calendar widget in the widget itself. This is just a way to show that, yes, we are in fact updating the bean on the server.

  27                <script type="text/javascript">
  28                    var cal1;
  29                    var loader = new YAHOO.util.YUILoader({
  30                        base: "http://ajax.googleapis.com/ajax/libs/yui/2.7.0/build/",
  31                        require: ["calendar"],
  32                        loadOptional: false,
  33                        combine: false,
  34                        filter: "RAW",
  35                        allowRollup: false,
  36                        onSuccess: function() {
  37                            try {
  38                                cal1 = new YAHOO.widget.Calendar("cal1", "cal1Container");
  39                                cal1.render();
  40                                cal1.selectEvent.subscribe(handleSelect, cal1, true);
  41                            } catch (e) {
  42                                alert(e);
  43                            }
  44                        },
  45                        // should a failure occur, the onFailure function will be executed
  46                        onFailure: function(o) {
  47                            alert("error: " + YAHOO.lang.dump(o));
  48                        }
  49                    });
  50    
  51                    // Calculate the dependency and insert the required scripts and css resources
  52                    // into the document
  53                    loader.insert();



With the exception of lines 36-44, this code is pretty much just YUI Loader boilerplate code. In fact, much of it can even be generated automatically by utilities on the main YUI site. All that this code is doing, is simply loading all of the JavaScript and CSS files required to run the Calendar widget.


Lines 36-44 set up the calendar, display it, and then register a listener on the widget. Line 40 says that we should call the selectHandler function, whenever the cal1 component has a select event.

  55                    function handleSelect(type,args,obj) {
  56                        var dates = args[0];
  57                        var date = dates[0];
  58                        var year = date[0], month = date[1], day = date[2];
  59    
  60                        var txtDate = document.getElementById("date");
  61                        txtDate.value = month + "/" + day + "/" + year;
  62                        try {
  63                            jsf.ajax.request("date",null,{render: 'out', execute: 'date'})
  64                        } catch (e) {
  65                            alert(e);
  66                        }
  67                    }
  68                </script>
  69            </h:form>
  70        </h:body>
  71    </html>


And this selectHandler function is the last part of the page. We get the date selected in the widget, assign it to the date hidden field, and then commit it to the server via the jsf.ajax.request call. Note that we also use that ajax call to update the output field as well – though I mentioned earlier that that was not strictly required – you could just use the YUI Calendar widget with the hidden field, skipping any additional display of values.


There’s more that can be done with this example – adding two way communication between the widget and the bean, for instance, or putting this into a component. But I’ve already spent a fair bit of text on this example, that’s a topic for another day.


As always, let me know if you have any questions about this example in the comments below.

(This article originally published on my java.net blog on August 9, 2009.)

Written by Jim Driscoll

February 9, 2010 at 9:33 PM

Posted in ajax, JSF, YUI

Including scripts in JSF 2 Ajax requests

leave a comment »

I’d wanted to blog some time ago about including scripts in your JSF ajax requests, but Hazem Saleh beat me to it. Hazem is the creator of the nifty Google Maps component for JSF, gmaps4jsf.

So, go and follow the link, but I’ll just add three short comments to Hazem’s blog:

  • In many popular ajax solutions for JSF, <script> tags were simply interpreted in place. This is not, for whatever reason, part of the JSF spec right now – so you’ll have to use one of the two ways that Hazem describes, in order for it to be a portable solution.
  • The first solution Hazem notes uses the event system for JSF client side – it simply adds an event listener that’s called every time a page is updated, and calls the eval for any included scripts.
  • The second solution is the “preferred” way that is specified in the spec – simply return the script you want to execute as part of the xml that goes to the client.

Hope this note helps someone trying to execute an arbitrary script on a JSF client page.

(This article originally published on my java.net blog on July 18, 2009.)

Written by Jim Driscoll

February 9, 2010 at 9:04 PM

Posted in ajax, JSF

A tale of two components (JSF2)

with one comment

Today, I’d like to take a look at two different ways to create a poll component. Poll components are a way to periodically update a page with new information. We’ll take a look at examples of these in a second, but first, a caveat: I’ve assumed throughout my blogs on Ajax components in JSF that you have at least a passing familiarity with JavaScript. This post assumes a bit more knowledge of JavaScript than some other posts. I’ll try to explain what I’m doing as I go along, but if you find yourself mystified by closures, I’d like to suggest the book JavaScript: The Good Parts. It’s a wonderful book, and quite short. Check it out.


With that out of the way, here’s how you’d use these two poll components within a page:

Count:<br/>
<h:outputText id="target" value="#{count.count}"/><br/>
<ez:polltag id="poll" interval="200" timeout="5000" render=":form:target"/>
<h:outputText id="target2" value="#{count.count2}"/>
<ez:poll id="poll2" interval="1000" timeout="10000" render="form:target2"/>

Let’s go over what this does: We have a two components, polltag and poll. They each have three attributes, interval (how often to refresh the target), timeout (when to stop), and render (the target we’ll refresh). These tags are identical in function, with the only difference being the format of their render attribute (more on that momentarily) and the method they use to make the Ajax call. Run this page, and you’ll see the numbers increment – one quickly, and the other more slowly (count.count just increments every time it’s accessed).


Let’s start by taking a look at the polltag component. I decided to start with just a quick, naive component that uses the Ajax tag. Let’s take a look at what that tag looks like (resources/poll/polltag.xhtml):

<cc:implementation>
    <span id="#{cc.clientId}">
    <h:outputScript name="poll/polltag.js" target="head" />
        <h:commandButton id="hidden" type="button" style="display: none;">
            <f:ajax render="#{cc.attrs.render}"/>
        </h:commandButton>
    </span>
    <script type="text/javascript">
        jsfdemo.polltag.init("#{cc.clientId}","#{cc.attrs.interval}", "#{cc.attrs.timeout}");
    </script>
</cc:implementation>


For those of you following my previous blogs, much of this isn’t new: We wrap the whole component to get a span on the page with the supplied id. We include a script (resources/poll/polltag.js) which adds the backing JavaScript. We also inject a small script which calls that backing JavaScript function. And that injected script includes the necessary context to allow multiple tags to be placed in the page.


But the new thing here is that we’re including a hidden button, and attaching an Ajax tag to it. That Ajax tag will then inject code that activates when the button is clicked. Since the button is hidden, we’ll “click” the button programatically, inside the init function. Let’s take a look at that backing JavaScript.

if (!window.jsfdemo) {
    var jsfdemo = {};
}

if (!jsfdemo.polltag) {
    jsfdemo.polltag = {};
}

if (!jsfdemo.polltag.init) {
    jsfdemo.polltag.init = function init(id, inc, to) {
        var componentID = id;
        var increment = inc;
        var timeout = to;
        var elapsed = 0;
        var token = null;

        // If increment isn't set, or it's less than some reasonable value (50) default to 200ms
        if (isNaN(increment) || increment <= 50) {
            increment = 200;
        }
        // If timeout isn't set, default to no timeout
        if (isNaN(timeout) || timeout == 0) {
            timeout = -1;
        }

        var poll = function poll() {
            var hiddenID = componentID + ":" + "hidden";
            var hidden = document.getElementById(hiddenID);
            hidden.click();  // this executes the ajax request
            if (timeout != -1) {
                // Not an accurate timeout - but simple to compute
                elapsed += increment;
                if (elapsed > timeout) {
                    window.clearInterval(token);
                }
            }
        }

        token = window.setInterval(poll, increment);
    }
}

OK, this is a little long, let’s break it down to see what’s going on here.

First, we do namespacing: by creating objects, and placing the function onto that object, we make sure that we don’t accidentally have two init() functions in a page – such as when we’re creating two different poll tags with init functions. We also need to check if those objects already exist before creating them – after all, we may want to have multiple namespaces placed onto the “jsfdemo” object.


Then, we define a module – we have an init() function, and inside that init() function, we also define a poll() function. The poll() function has access to the variables inside the init() function, but calling the init function multiple times results in multiple contexts. This is a pretty common pattern in JavaScript, but it does look awkward to folks coming from Java.


At the end of the file, after setting up the poll() function, we have the line:

token = window.setInterval(poll, increment);


Which sets up the poll – we’re simply using the JavaScript setInterval function to periodically call the poll() function, every increment milliseconds.


When the poll function is called, we find the button, and click it. This will, in turn, trigger the Ajax call. Then, we determine if the timeout time has come, and if it has, we turn off the timer with the clearInterval call.


OK, a little kludgy – but it works, after a fashion. There are some problems with this approach: Since we’re using the f:ajax tag, we need to use the UIComponent.findComponent syntax for locating the target to update – some may prefer this, some won’t. And while having a button that you could “unhide” to restart the poll might be handy, in general it’s just cluttering up your page. Also, if the server stops responding for some reason, you’ll get pummeled with error alerts if you’re in development mode.


So, let’s go ahead and rewrite this to instead use the jsf.ajax.request function, provided by jsf.js in JSF 2.


We’ll only have to make a few quick changes to do this, as well as adding error handling. First, in the component page, we’ll say add an output script call. And, we’ll also change the call to init to be wrapped inside a jsf.ajax.addOnError function call. This will add a function to the list of listeners that get called if there’s an error on the page. Note that the init function itself is not the function that will get added – rather, it’s return value will be what’s added. And we’ll make that return value be a function (you’ll see it in a second). We also remove all the markup associated with the button.

<cc:implementation>
    <span id="#{cc.clientId}">
        <h:outputScript name="jsf.js" library="javax.faces" target="head"/>
        <h:outputScript name="poll/poll.js" target="head" />
    </span>
    <script type="text/javascript">
        /* <![CDATA[ */
        jsf.ajax.addOnError(jsfdemo.poll.init("#{cc.clientId}","#{cc.attrs.interval}", "#{cc.attrs.timeout}", "#{cc.attrs.render}"));
        /* ]]> */
    </script>
</cc:implementation>

In the backing JavaScript, we’re going to have to make two changes. We’ll have to change the poll function, and we’ll have to add a return value to the init function. Here’s the entirety of the backing JavaScript file:

if (!window.jsfdemo) {
    var jsfdemo = {};
}

if (!jsfdemo.poll) {
    jsfdemo.poll = {};
}

if (!jsfdemo.poll.init) {
    jsfdemo.poll.init = function init(id, inc, to, rend) {
        var componentID = id;
        var increment = inc;
        var timeout = to;
        var elapsed = 0;
        var token = null;
        var render = rend;

        // If increment isn't set, or it's less than some reasonable value (50) default to 200ms
        if (isNaN(increment) || increment <= 50) {
            increment = 200;
        }
        // If timeout isn't set, default to no timeout
        if (isNaN(timeout) || timeout == 0) {
            timeout = -1;
        }

        var poll = function poll() {
            jsf.ajax.request(componentID, null, {render: render});
            if (timeout != -1) {
                // Not an accurate timeout - but simple to compute
                elapsed += increment;
                if (elapsed > timeout) {
                    window.clearInterval(token);
                }
            }
        }

        token = window.setInterval(poll, increment);

        return function cancelPoll(data) {
            if (data.source.id == componentID) {
                window.clearInterval(token);
            }
        }
    }
}

Let’s look at the return value first:

return function cancelPoll(data) {
    if (data.source.id == componentID) {
        window.clearInterval(token);
    }
}


We add this at the end of the init function – which means that init will return this function as it’s return value, and that this function will be what’s added to the list of listeners that get called when there’s an error. Because this function will get called regardless of what component causes the error, we add a check to make sure that the current component is the one that got the error. And, as in the poll function, because this function is defined inside init, it has access to all of the context that’s there when init is called – in this case, the componentID variable, passed in by the script tag in the component.


The changes for the poll function to use jsf.ajax.request are relatively straightforward:

var poll = function poll() {
    jsf.ajax.request(componentID, null, {render: render});
    if (timeout != -1) {
        // Not an accurate timeout - but simple to compute
        elapsed += increment;
        if (elapsed > timeout) {
            window.clearInterval(token);
        }
    }
}


Much simpler than the corresponding code surrounding the tag method.


As always, this code can be found in the jsf-demo/ajax-components directory of the Project Mojarra codebase. You’ll find this and much more code there, including most of the code I’ve blogged about in the past.


If you have questions, please let me know in the comments section.

(This article originally published on my java.net blog on July 3, 2009.)

Written by Jim Driscoll

February 9, 2010 at 9:03 PM

Posted in ajax, JSF

Automatic compression of jsf.js

leave a comment »

Just a quick note that we’ve now added automatic compression of the jsf.js file served by JSF 2. The file size of jsf.js, 71k uncompressed, comes to about 16k compressed (there are a lot of comments in there).


There is no user action required to make this happen: If the Project stage is Development, the file is served uncompressed (for ease in debugging with something like Firebug), but if the Project stage is anything else, then the file is compressed (and essentially unreadable, since besides stripping all comments, variable names are stripped, as well as all line breaks).


To enable Project Stage as Development, place the following in your web.xml file:


    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

(This article originally published on my java.net blog on July 3, 2009.)

Written by Jim Driscoll

February 9, 2010 at 9:00 PM

Posted in ajax, JSF

Follow

Get every new post delivered to your Inbox.

Join 411 other followers