<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>LogikDevelopment &#187; JSF</title>
	<atom:link href="http://www.logikdev.com/tag/jsf/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.logikdev.com</link>
	<description>&#34;Il n&#039;y a pas de problème, il n&#039;y a que des solutions. L&#039;esprit de l&#039;homme invente ensuite le problème.&#34; André Gide</description>
	<lastBuildDate>Tue, 20 Dec 2011 12:25:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Delete the components holding unwanted state</title>
		<link>http://www.logikdev.com/2011/06/13/delete-the-components-holding-unwanted-state/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=delete-the-components-holding-unwanted-state</link>
		<comments>http://www.logikdev.com/2011/06/13/delete-the-components-holding-unwanted-state/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 21:11:48 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[component holding state]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[MyFaces]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=337</guid>
		<description><![CDATA[This is a small addition to a problem discussed on the MyFaces Wiki: http://wiki.apache.org/myfaces/ClearInputComponents Just in case the page is removed from the Wiki, please see below a copy of the problem description: Sometimes you want to provide a command component (eg a link or button) that performs some server action, and renders the same [...]]]></description>
			<content:encoded><![CDATA[<p>This is a small addition to a problem discussed on the MyFaces Wiki: <a href="http://wiki.apache.org/myfaces/ClearInputComponents">http://wiki.apache.org/myfaces/ClearInputComponents</a></p>
<p>Just in case the page is removed from the Wiki, please see below a copy of the problem description:</p>
<blockquote><p>
Sometimes you want to provide a command component (eg a link or button) that performs some server action, and renders the same page but with completely &#8220;fresh&#8221; values for all components.<br />
<br/>When using command components with the normal immediate setting (false), achieving this is just a matter of clearing the beans that the JSF component value attributes access. Any values entered by the user will have been pushed into these beans as part of the Update Model phase, so the components themselves will not be holding any information about submitted data. The action method associated with the command is then run which resets the model, and when the components render themselves they will draw fresh data from the (reset) beans.<br />
<br/>Note that because data is being pushed into the model, the validation phase must run, and therefore any invalid data in the page will cause the action to be skipped, and the page is redisplayed with the validation errors displayed. This is not generally the desired behaviour for a &#8220;clear&#8221; type operation! The solution is to set attribute immediate=true on the command so that its associated action is invoked before validation is applied to the input components in the same view (see <a href="http://wiki.apache.org/myfaces/How_The_Immediate_Attribute_Works">How_The_Immediate_Attribute_Works</a>).<br />
<br/>However when using command components with immediate=true, things become more complex. All components will retrieve the raw submitted values submitted by the user, but the immediate command will then run before they can be pushed into the backing beans; the components therefore remember this data. When the (immediate) action causes navigation to another view then this is no problem; these components will be discarded anyway. However if the action method causes JSF to go directly to the render phase &#8216;of the same view&#8217; [by calling facesContext.renderResponse()], then the components will behave as they do for a validation failure &#8211; by displaying the value cached in the component rather than fetching data from the backing bean.
</p></blockquote>
<p>MyFaces gave four solutions to this problem, but the one I used is the following:</p>
<blockquote><p>
Find the parent component of the problem inputs, and call<br />
<code>parentComponent.getChildren().clear();</code><br />
<br/>During the render phase, new instances of these child components will then be created, while other components will not be affected.<br />
<br/>This is effectively the same as the above solution, but discards a selected subset of components rather than the UI!ViewRoot.<br />
<br/>Obtaining the parent component to discard can be done via binding. Alternatively, the &#8220;action listener&#8221; form of callback can be used for the command; this is passed an ActionEvent from which the command component that was clicked can be found. A call to &#8220;findComponent&#8221; can be made on this to locate the desired parent component by id, or other similar solutions.
</p></blockquote>
<p>All of this is good and well but what if you don&#8217;t have the component object but only the name of the form? How would you call the <code>clear</code> method then?</p>
<p>This is the reason why I wrote the code below:</p>
<pre class="brush: java; title: ; notranslate">
/**
 * Return the UIComponent that represents the root of the UIComponent tree.
 * @return the UIComponent that represents the root of the UIComponent tree
 */
public static UIViewRoot getUIViewRoot() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    return facesContext != null ? facesContext.getViewRoot() : null;
}

/**
 * Search for a component in the UIComponent tree
 * @param parentComponent the parent component
 * @param componentId the component identifier we look for
 * @return the component found
 */
private static UIComponent findComponent(UIComponent parentComponent, String componentId) {
    if (parentComponent != null) {
        if (componentId.equals(parentComponent.getId())) {
            return parentComponent;
        }
        for (UIComponent child : parentComponent.getChildren()) {
            UIComponent component = findComponent(child, componentId);
            if (component != null) {
                return component;
            }
        }
    }
    return null;
}

/**
 * Deletes components holding unwanted state
 * @param componentId the component identifier
 */
public static void deleteComponentsHoldingUnwantedState(UIComponent parentComponent) {
    if (parentComponent != null) {
        parentComponent.getChildren().clear();
    }
}

/**
 * Deletes components holding unwanted state
 * @param componentId the component identifier
 */
public static void deleteComponentsHoldingUnwantedState(String componentId) {
    deleteComponentsHoldingUnwantedState(findComponent(getUIViewRoot(), componentId));
}
</pre>
<p>The last method of the code above will allow you to delete all the components holding unwanted state of a form simply by passing its name.<br />
For example:</p>
<pre class="brush: java; light: true; title: ; notranslate">
deleteComponentsHoldingUnwantedState(&quot;myform&quot;);
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2011/06/13/delete-the-components-holding-unwanted-state/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Upgrade to RichFaces 3.3.3.Final</title>
		<link>http://www.logikdev.com/2010/10/20/upgrade-to-richfaces-3-3-3-final/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=upgrade-to-richfaces-3-3-3-final</link>
		<comments>http://www.logikdev.com/2010/10/20/upgrade-to-richfaces-3-3-3-final/#comments</comments>
		<pubDate>Wed, 20 Oct 2010 22:04:02 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[MyFaces]]></category>
		<category><![CDATA[pom.xml]]></category>
		<category><![CDATA[RichFaces]]></category>
		<category><![CDATA[SequenceDataAdaptor]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=858</guid>
		<description><![CDATA[From time to time, it is good to upgrade the application libraries to the latest stable version. Especially the frontend libraries as the browsers are constantly involving and new ones are coming on the market. This is why I wanted to upgrade the RichFaces library on one of my web application which was still using [...]]]></description>
			<content:encoded><![CDATA[<p>From time to time, it is good to upgrade the application libraries to the latest stable version. Especially the frontend libraries as the browsers are constantly involving and new ones are coming on the market.</p>
<p>This is why I wanted to upgrade the RichFaces library on one of my web application which was still using the version 3.3.0.GA with JSF/MyFaces 1.2.5.<br />
The RichFaces dependency was looking like the following in my <code>pom.xml</code> file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.richfaces.ui&lt;/groupId&gt;
    &lt;artifactId&gt;richfaces-ui&lt;/artifactId&gt;
    &lt;version&gt;3.3.0.GA&lt;/version&gt;
    &lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>The upgrade should be straightforward.<br />
But when changing to the version 3.3.3.Final, I got the following error:</p>
<pre style="height:250px;">
2010-10-13 15:56:14.959::WARN:  Error starting handlers
java.lang.NoClassDefFoundError: org/ajax4jsf/component/SequenceDataAdaptor
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
	at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:366)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
	at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:366)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
	at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:366)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:247)
	at org.apache.myfaces.shared_impl.util.ClassUtils.classForName(ClassUtils.java:132)
	at org.apache.myfaces.shared_impl.util.ClassUtils.simpleClassForName(ClassUtils.java:158)
	at org.apache.myfaces.application.ApplicationImpl.addComponent(ApplicationImpl.java:564)
	at org.apache.myfaces.config.FacesConfigurator.configureApplication(FacesConfigurator.java:650)
	at org.apache.myfaces.config.FacesConfigurator.configure(FacesConfigurator.java:277)
	at org.apache.myfaces.webapp.AbstractFacesInitializer.buildConfiguration(AbstractFacesInitializer.java:131)
	at org.apache.myfaces.webapp.Jsp21FacesInitializer.initContainerIntegration(Jsp21FacesInitializer.java:64)
	at org.apache.myfaces.webapp.AbstractFacesInitializer.initFaces(AbstractFacesInitializer.java:83)
	at org.apache.myfaces.webapp.StartupServletContextListener.contextInitialized(StartupServletContextListener.java:72)
	at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:540)
	at org.mortbay.jetty.servlet.Context.startContext(Context.java:135)
	at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1220)
	at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:510)
	at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448)
	at org.mortbay.jetty.plugin.Jetty6PluginWebAppContext.doStart(Jetty6PluginWebAppContext.java:110)
	at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
	at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)
	at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156)
	at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
	at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152)
	at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
	at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:117)
	at org.mortbay.jetty.Server.doStart(Server.java:222)
	at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:40)
	at org.mortbay.jetty.plugin.Jetty6PluginServer.start(Jetty6PluginServer.java:132)
	at org.mortbay.jetty.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:357)
	at org.mortbay.jetty.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:293)
	at org.mortbay.jetty.plugin.AbstractJettyRunMojo.execute(AbstractJettyRunMojo.java:203)
	at org.mortbay.jetty.plugin.Jetty6RunMojo.execute(Jetty6RunMojo.java:182)
	at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
	at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
	at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:512)
	at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:482)
	at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
	at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
	at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
	at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
	at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
	at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
	at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
	at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
	at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: java.lang.ClassNotFoundException: org.ajax4jsf.component.SequenceDataAdaptor
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
	at org.codehaus.classworlds.RealmClassLoader.loadClassDirect(RealmClassLoader.java:195)
	at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:255)
	at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:274)
	at org.codehaus.classworlds.RealmClassLoader.loadClass(RealmClassLoader.java:214)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:375)
	at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
	... 82 more
</pre>
<p><br/>What happened here? I simply changed the version number and it now does NOT work! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /><br />
Looking at the exception, it seems that it cannot find the class <code>org.ajax4jsf.component.SequenceDataAdaptor</code> which is part of the <code>richfaces-impl</code> library. Why not?</p>
<p>Well, in fact, it is quite simple! It appears that from the version 3.3.3 of RichFaces, you now have to specifically add the <code>richfaces-impl</code> dependency to your <code>pom.xml</code> file such as:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
    &lt;groupId&gt;org.richfaces.ui&lt;/groupId&gt;
    &lt;artifactId&gt;richfaces-ui&lt;/artifactId&gt;
    &lt;version&gt;3.3.3.Final&lt;/version&gt;
    &lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.richfaces.framework&lt;/groupId&gt;
    &lt;artifactId&gt;richfaces-impl&lt;/artifactId&gt;
    &lt;version&gt;3.3.3.Final&lt;/version&gt;
    &lt;scope&gt;compile&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>Why do we have to manually add this dependency? This is because the new version of RichFaces allows you to use JSF 2.0 instead of JSF 1.2. To do that, simply add the library <code>richfaces-impl-jsf2</code> instead of <code>richfaces-impl</code> in your <code>pom.xml</code> file.</p>
<p>Please click on the following link for the JBoss manual about this configuration:<br />
<a href="http://community.jboss.org/wiki/HowtoaddRichFaces33xtomavenbasedproject" alt="How to add RichFaces 3.3.x to maven based project" title="How to add RichFaces 3.3.x to maven based project">http://community.jboss.org/wiki/HowtoaddRichFaces33xtomavenbasedproject</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2010/10/20/upgrade-to-richfaces-3-3-3-final/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>loadBundle&#8217;s behaviour with JSTL tags</title>
		<link>http://www.logikdev.com/2010/10/02/loadbundles-behaviour-with-jstl-tags/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=loadbundles-behaviour-with-jstl-tags</link>
		<comments>http://www.logikdev.com/2010/10/02/loadbundles-behaviour-with-jstl-tags/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 11:48:32 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[JSTL]]></category>
		<category><![CDATA[loadBundle]]></category>
		<category><![CDATA[resource bundle]]></category>
		<category><![CDATA[RichFaces]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=806</guid>
		<description><![CDATA[Let&#8217;s start with a bit of knowledge. f:loadBundle is a JSF tag which loads a resource bundle and saves it as a variable in the request scope. The RichFaces a4j:loadBundle tag is a substitution for the f:loadBundle tag and allows to use reference to bundle messages during the Ajax re-rendering. When I discovered the RichFaces [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s start with a bit of knowledge.<br />
<code>f:loadBundle</code> is a JSF tag which loads a resource bundle and saves it as a variable in the request scope. The RichFaces <code>a4j:loadBundle</code> tag is a substitution for the <code>f:loadBundle</code> tag and allows to use reference to bundle messages during the Ajax re-rendering.</p>
<p>When I discovered the RichFaces tag, I immediately replaced all the <code>f:loadBundle</code> tags by <code>a4j:loadBundle</code>. Was I right? I thought at first, but then I got a problem. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>The problem was appearing when I started mixing RichFaces and JSF tags.<br />
For example, let&#8217;s take the following resource bundle:</p>
<pre class="brush: plain; title: ; notranslate">active=true</pre>
<p>And the following code:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a4j:loadBundle basename=&quot;Messages&quot; var=&quot;msg&quot; /&gt;
Active is #{msg.active} --
&lt;c:if test=&quot;#{msg.active}&quot;&gt;
	Hello World!
&lt;/c:if&gt;
</pre>
<p>This displays &#8216;<code>Active is true --</code>&#8216;.<br />
What is wrong there? The active message is true but the <code>c:if</code> condition failed!  <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_eek.gif' alt='8-O' class='wp-smiley' /> </p>
<p>Let&#8217;s now try the following:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a4j:loadBundle basename=&quot;Messages&quot; var=&quot;msg&quot; /&gt;
Active is #{msg.active} --
&lt;c:if test=&quot;#{empty msg.active}&quot;&gt;
	Hello World!
&lt;/c:if&gt;
</pre>
<p>This displays &#8216;<code>Active is true -- Hello World!</code>&#8216;.<br />
What does that mean? It seems that JSTL doesn&#8217;t get the value of the <code>active</code> message but gets an empty string instead!</p>
<p>In conclusion, if the resource bundle is loading using the RichFaces tag, the messages will be not visible by the JSTL tags.<br />
To fix this problem, you will have to also load the resource bundle using the JSF tag:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;a4j:loadBundle basename=&quot;Messages&quot; var=&quot;msg&quot; /&gt;
&lt;f:loadBundle basename=&quot;Messages&quot; var=&quot;msg&quot; /&gt;
Active is #{msg.active} --
&lt;c:if test=&quot;#{msg.active}&quot;&gt;
	Hello World!
&lt;/c:if&gt;
</pre>
<p>As expected, this displays &#8216;<code>Active is true -- Hello World!</code>&#8216;. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2010/10/02/loadbundles-behaviour-with-jstl-tags/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clock change affecting date display</title>
		<link>http://www.logikdev.com/2010/09/18/clock-change-affecting-date-display/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=clock-change-affecting-date-display</link>
		<comments>http://www.logikdev.com/2010/09/18/clock-change-affecting-date-display/#comments</comments>
		<pubDate>Sat, 18 Sep 2010 12:04:16 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[convertDateTime]]></category>
		<category><![CDATA[GMT]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[outputText]]></category>
		<category><![CDATA[time zone]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=771</guid>
		<description><![CDATA[This is a very particular problem which happens only during the summer and not even in all the countries ! The problem is related to the Daylight Saving Time (DST), also called British Summer Time (BST): Daylight saving time is the practice of temporarily advancing clocks so that afternoons have more daylight and mornings have [...]]]></description>
			<content:encoded><![CDATA[<p>This is a very particular problem which happens only during the summer and not even in all the countries ! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /><br />
The problem is related to the Daylight Saving Time (DST), also called British Summer Time (BST):</p>
<blockquote><p>
Daylight saving time is the practice of temporarily advancing clocks so that afternoons have more daylight and mornings have less. Typically clocks are adjusted forward one hour near the start of spring and are adjusted backward in autumn.
</p></blockquote>
<p>Okay, so how do we display dates with JSF?<br />
Let&#8217;s take this can&#8217;t-be-simpler bean:</p>
<pre class="brush: java; title: ; notranslate">
public class MyBean {
	public Date getDate() {
		return new Date();
	}
}
</pre>
<p>And let&#8217;s insert the following code in a JSF page:</p>
<pre class="brush: xml; title: ; notranslate">
#{myBean.date}
</pre>
<p>The result is <code>Fri Sep 17 20:03:14 BST 2010</code> (when I wrote this article).<br />
If I check my clock, the date and time above are correct.<br />
So far so good. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Let&#8217;s now use the <code>h:outputText</code> tag from JSF:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;h:outputText value=&quot;#{myBean.date}&quot;/&gt;
</pre>
<p>The result is <code>Sep 17, 2010</code>.<br />
Alright, the date is correct but the time is not displayed&#8230;</p>
<p>Let&#8217;s use the <code>f:convertDateTime</code> tag to also display the time:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;h:outputText value=&quot;#{myBean.date}&quot;&gt;
	&lt;f:convertDateTime pattern=&quot;E MMM dd HH:mm:ss z yyyy&quot; /&gt;
&lt;/h:outputText&gt;
</pre>
<p>The result is <code>Fri Sep 17 19:03:14 GMT 2010</code>.<br />
What can we see here? The time went one hour backward!<br />
Why that? well, simply because the date is now displayed in GMT, instead of BST earlier.</p>
<p>So, this means that the <code>h:outputText</code> tag is displaying the date in GMT by default, which would be fine in winter but not in summer.<br />
In order to fix this behaviour, you need to add the attribute <code>timeZone</code> to the <code>f:convertDateTime</code> tag such as:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;h:outputText value=&quot;#{myBean.date}&quot;&gt;
	&lt;f:convertDateTime pattern=&quot;E MMM dd HH:mm:ss z yyyy&quot; timeZone=&quot;GB&quot; /&gt;
&lt;/h:outputText&gt;
</pre>
<p>Note that if you put <code>BST</code> instead of <code>GB</code> in the <code>timeZone</code> attribute, the time zone is going to be actually set to <strong>BDST</strong> which stands for Bangladesh Daylight Saving Time! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2010/09/18/clock-change-affecting-date-display/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to configure JSF to get the browser Back button working</title>
		<link>http://www.logikdev.com/2010/06/23/configure-jsf-to-get-the-back-button-working/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=configure-jsf-to-get-the-back-button-working</link>
		<comments>http://www.logikdev.com/2010/06/23/configure-jsf-to-get-the-back-button-working/#comments</comments>
		<pubDate>Wed, 23 Jun 2010 20:03:56 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Back button]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[MyFaces]]></category>
		<category><![CDATA[numberOfViewsInSession]]></category>
		<category><![CDATA[RichFaces]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=615</guid>
		<description><![CDATA[Lately, I had a problem with one of my JSF applications which is using RichFaces. The problem was happening when the user was hitting the browser Back button. Well, you would say that it is a usual problem in web development. But still, because we cannot disable the browser Back button, the web application needs [...]]]></description>
			<content:encoded><![CDATA[<p>Lately, I had a problem with one of my JSF applications which is using RichFaces.<br />
The problem was happening when the user was hitting the browser Back button. Well, you would say that it is a usual problem in web development. But still, because we cannot disable the browser Back button, the web application needs to work fine if the user decides to click on it!</p>
<p>Anyway, let&#8217;s get back on topic. As I said, the problem occurred if the user was clicking on the Back button but the funniest thing is it was happening when he was clicking twice on it! Why did it work fine when clicking once but not twice? <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> </p>
<p>The solution is quite simple actually.<br />
It was coming from one of the options in MyFaces configuration: <code>com.sun.faces.numberOfViewsInSession</code>.<br />
Here is a quick explanation of this option:</p>
<blockquote><p>
<strong>com.sun.faces.numberOfViewsInSession</strong><br />
Specifies the number of views that are stored in the session when Server-Side State Saving is used. If set to true while client-side state saving is being used, reduces the number of bytes sent to the client by compressing the state before it is encoded and written as a hidden field. The default for this parameter is 15.
</p></blockquote>
<p>So basically, JSF is storing each page previously viewed by the user in session. And, as you can see from the description above, JSF will stored a maximum of <strong>15</strong> pages by default. However, it was set to <strong>1</strong> in my application, which means only ONE page would be stored&#8230;<br />
This was obviously the reason why the application was working fine if the user was clicking only once on the Back button but not twice! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p>For the same reason, you should also check the option <code>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</code> which is default to 20:</p>
<blockquote><p>
<strong>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</strong><br />
Defines the number of the latest views that are stored in session. This option is only applicable if the state saving method is set to server. The default for this parameter is 20.
</p></blockquote>
<p>For more information about JSF options, please have a look at the following page:<br />
<a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/rweb_jsfengine.html">http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/rweb_jsfengine.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2010/06/23/configure-jsf-to-get-the-back-button-working/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The message tags of MyFaces and RichFaces</title>
		<link>http://www.logikdev.com/2010/05/06/message-tags-of-myfaces-and-richfaces/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=message-tags-of-myfaces-and-richfaces</link>
		<comments>http://www.logikdev.com/2010/05/06/message-tags-of-myfaces-and-richfaces/#comments</comments>
		<pubDate>Thu, 06 May 2010 19:25:37 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[FacesMessage]]></category>
		<category><![CDATA[Html]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[message tag]]></category>
		<category><![CDATA[MyFaces]]></category>
		<category><![CDATA[RichFaces]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=472</guid>
		<description><![CDATA[Working on an application using MyFaces and RichFaces, I had no choice but understand what is the difference between the message tag provided by Myfaces (h:message) and the message tag overridden by RichFaces (rich:message). These tags allow to display information about the first FacesMessage that is assigned to the component referenced by the &#8220;for&#8221; attribute. [...]]]></description>
			<content:encoded><![CDATA[<p>Working on an application using MyFaces and RichFaces, I had no choice but understand what is the difference between the message tag provided by Myfaces (<code>h:message</code>) and the message tag overridden by RichFaces (<code>rich:message</code>).</p>
<p>These tags allow to display information about the first FacesMessage that is assigned to the component referenced by the &#8220;for&#8221; attribute. The difference is that the RichFaces tag has some extra functionalities such as Ajax rendering, error markers and predefined css class names.<br />
Have a look at the following page for more details: <a target="_blank" href="http://livedemo.exadel.com/richfaces-demo/richfaces/message.jsf">http://livedemo.exadel.com/richfaces-demo/richfaces/message.jsf</a></p>
<p>This is all nice and well but it is not the only difference. Indeed, the HTML code generated by both these frameworks will also be different!</p>
<p>First of all, let&#8217;s see how the tag <code>&lt;h:message styleClass="errormsg" for="element"/&gt;</code> will be transformed. If there is no message to display, nothing will be generated (which is a good behaviour). However, if a message is present, the tag will be replaced by the following HTML code:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;span class=&quot;errormsg&quot;&gt;Required.&lt;/span&gt;
</pre>
<p>So far, so good!</p>
<p>But now let&#8217;s check what code RichFaces is generating for the tag <code>&lt;rich:message styleClass="errormsg" for="element"/&gt;</code>.<br />
The following is the code created if there is NO message to render:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;span class=&quot;rich-message errormsg&quot; id=&quot;form:j_id255&quot;&gt;
    &lt;span class=&quot;rich-message-label&quot;&gt;&lt;/span&gt;
&lt;/span&gt;
</pre>
<p>And here is the code which will replace the RichFaces tag if there is a message to display:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;span class=&quot;rich-message errormsg&quot; id=&quot;form:j_id255&quot;&gt;
    &lt;span class=&quot;rich-message-label&quot;&gt;Required.&lt;/span&gt;
&lt;/span&gt;
</pre>
<p>As you can see, the main difference is that RichFaces is wrapping the original <code>span</code> tag into another <code>span</code> tag. But, it is also generating some code even if there is no message to display! You would ask why is it doing that? The response is simple. The wrapper span element is necessary for RichFaces to Ajax-render the message tag if an error message has to be displayed for the targeting element.</p>
<p>So make sure you don&#8217;t put any padding or margin style in your custom CSS class which I called &#8216;errormsg&#8217; in my example. Otherwise, you might have a gap when you were expecting nothing&#8230; (this happened to me) <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2010/05/06/message-tags-of-myfaces-and-richfaces/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to personalise the URLs with Faces Navigation?</title>
		<link>http://www.logikdev.com/2010/03/24/how-to-personalise-the-urls-with-faces-navigation/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-personalise-the-urls-with-faces-navigation</link>
		<comments>http://www.logikdev.com/2010/03/24/how-to-personalise-the-urls-with-faces-navigation/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 20:01:29 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[EL expressions]]></category>
		<category><![CDATA[Faces Navigation]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[SEO]]></category>
		<category><![CDATA[view handler]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=418</guid>
		<description><![CDATA[This is an important question if you want to have search engine friendly URLs on your website! But unfortunately, the solution is not straightforward with JavaServer Faces (JSF). First of all, for security reason JSF doesn&#8217;t allow you to use the GET method for your forms. I didn&#8217;t really understand why but this is very [...]]]></description>
			<content:encoded><![CDATA[<p>This is an important question if you want to have search engine friendly URLs on your website!<br />
But unfortunately, the solution is not straightforward with JavaServer Faces (JSF). <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>First of all, for security reason JSF doesn&#8217;t allow you to use the GET method for your forms. I didn&#8217;t really understand why but this is very (too) restrictive!<br />
Can you imagine Google doing the same thing? We would have the same URL for every search terms <code>http://www.google.co.uk/search</code> instead of something like <code>http://www.google.co.uk/search?hl=en&amp;safe=off&amp;esrch=FT1&amp;q=test&amp;meta=&amp;aq=f&amp;aqi=g10&amp;aql=&amp;oq=&amp;gs_rfai=</code>.<br />
It wouldn&#8217;t be very easy to share a search page with a friend if Google was using the POST method. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>So the question is how to get around this JSF limitation?</p>
<p>Let&#8217;s take a look at how would look our <code>faces-navigation.xml</code> file for a search page:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;navigation-case&gt;
    &lt;from-action&gt;#{searchBean.searchAction}&lt;/from-action&gt;
    &lt;from-outcome&gt;success&lt;/from-outcome&gt;
    &lt;to-view-id&gt;/search.xhtml&lt;/to-view-id&gt;
    &lt;redirect /&gt;
&lt;/navigation-case&gt;
</pre>
<p>In this example, all the JSF elements calling the action <code>searchBean.searchAction</code> will be redirected to the <code>search.xhtml</code> page.<br />
But, how are we going to get the search parameters into the URL?</p>
<p>Ideally, it would be great to be able to do something like the following:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;navigation-case&gt;
    &lt;from-action&gt;#{searchBean.searchAction}&lt;/from-action&gt;
    &lt;from-outcome&gt;success&lt;/from-outcome&gt;
    &lt;to-view-id&gt;/search.xhtml?q=#{param.q}&lt;/to-view-id&gt;
    &lt;redirect /&gt;
&lt;/navigation-case&gt;
</pre>
<p>This solution would allow us to inject EL expressions into the URL before the page is redirected to the destination page.<br />
In order to do this, we need to create our own view handler and register it to our application.  <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_cool.gif' alt='8-)' class='wp-smiley' /> </p>
<p>The code below is the view handler class which also includes some comments:</p>
<pre class="brush: java; title: ; notranslate">
package com.logikdev.gui.handler;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.ViewHandler;
import javax.faces.context.FacesContext;

import com.sun.facelets.FaceletViewHandler;

/**
 * Overrides the Facelet view handler to support EL expressions in URLs.
 * @author Stéphane Moreau
 */
public class DynamicViewHandler extends FaceletViewHandler {

	public DynamicViewHandler(ViewHandler parent) {
		super(parent);
	}

	/* (non-Javadoc)
	 * @see com.sun.facelets.FaceletViewHandler#getActionURL(javax.faces.context.FacesContext, java.lang.String)
	 */
	@Override
	public String getActionURL(FacesContext context, String viewId) {
		String queryString = null;

		// Replace the EL expressions in the URL
		ExpressionFactory expressionFactory = context.getApplication().getExpressionFactory();
		ValueExpression valueExpression = expressionFactory.createValueExpression(context.getELContext(), viewId, String.class);
		String result = (String) valueExpression.getValue(context.getELContext());

		// Separate the query string from the URL
		int dotIndex = result.lastIndexOf('.');
		int questionMarkIndex = result.indexOf('?');
		if (questionMarkIndex != -1) {
			queryString = result.substring(questionMarkIndex, dotIndex);
			viewId = result.substring(0, questionMarkIndex) + result.substring(dotIndex);
		}

		// Call the parent without the query string
		result = super.getActionURL(context, viewId);

		// Put back the query string at the end of the URL
		if (queryString != null) {
			result += queryString;
		}

		return result;
	}

}
</pre>
<p>And the following is the code to put in the <code>faces-config.xml</code> file in order to register the newly created view handler to the application:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;application&gt;
	&lt;variable-resolver&gt;org.springframework.web.jsf.DelegatingVariableResolver&lt;/variable-resolver&gt;
	&lt;view-handler&gt;com.logikdev.gui.handler.DynamicViewHandler&lt;/view-handler&gt;
&lt;/application&gt;
</pre>
<p><strong>One last thing!</strong><br />
This view handler also has a limitation which I wasn&#8217;t able to fix. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  The file extension has to ALWAYS be placed at the end of the <code>to-view-id</code> URL! The view handler will then put it back before the question mark.<br />
For example:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;navigation-case&gt;
	&lt;from-action&gt;#{searchBean.searchAction}&lt;/from-action&gt;
	&lt;from-outcome&gt;success&lt;/from-outcome&gt;
	&lt;!-- The extension has to be at the end --&gt;
	&lt;to-view-id&gt;/search?q=#{param.q}.xhtml&lt;/to-view-id&gt;
	&lt;redirect /&gt;
&lt;/navigation-case&gt;
</pre>
<p>If you perform a search on &#8216;jsf&#8217; with the above navigation rule, the user will be redirected to the page <code>/search.xhtml?q=jsf</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2010/03/24/how-to-personalise-the-urls-with-faces-navigation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>No saved view state</title>
		<link>http://www.logikdev.com/2009/11/25/no-saved-view-state/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=no-saved-view-state</link>
		<comments>http://www.logikdev.com/2009/11/25/no-saved-view-state/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 22:03:21 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[a4j:poll]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[BUILD_BEFORE_RESTORE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[No saved view state]]></category>
		<category><![CDATA[RichFaces]]></category>
		<category><![CDATA[session time out]]></category>
		<category><![CDATA[ViewExpiredException]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=88</guid>
		<description><![CDATA[How many of you did already get the following error when working with JSF? I would be surprised if none of you got it at least once! HTTP ERROR: 500 /web/home.htmlNo saved view state could be found for the view identifier: /web/home.html RequestURI=/web/home.html Caused by: javax.faces.application.ViewExpiredException: /web/home.htmlNo saved view state could be found for the [...]]]></description>
			<content:encoded><![CDATA[<p>How many of you did already get the following error when working with JSF?<br />
I would be surprised if none of you got it at least once! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<pre><span style="font-size: large;"><strong>HTTP ERROR: 500</strong></span>

/web/home.htmlNo saved view state could be found for the view identifier: /web/home.html

RequestURI=/web/home.html
<strong>
Caused by:
</strong>
javax.faces.application.ViewExpiredException: /web/home.htmlNo saved view state could be found for the view identifier: /web/home.html
	at org.apache.myfaces.lifecycle.RestoreViewExecutor.execute(RestoreViewExecutor.java:88)
	at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:103)
	at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:76)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:151)
	at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
	at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1093)
	at org.apache.myfaces.webapp.filter.ExtensionsFilter.doFilter(ExtensionsFilter.java:341)
	at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:83)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
	at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
	at org.ajax4jsf.webapp.BaseXMLFilter.doXmlFilter(BaseXMLFilter.java:178)
	at org.ajax4jsf.webapp.BaseFilter.handleRequest(BaseFilter.java:290)
	at org.ajax4jsf.webapp.BaseFilter.processUploadsAndHandleRequest(BaseFilter.java:368)
	at org.ajax4jsf.webapp.BaseFilter.doFilter(BaseFilter.java:495)
	at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084)
	...</pre>
<p>This very common error happens because your session has timed out. As you probably already know, JSF is storing the view state of your page in session. Obviously, when the session has timed out, it can&#8217;t restore the view state and so throws a <code>ViewExpiredException</code>.</p>
<p>The solution for this problem is to add the following lines in your web.xml file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;context-param&gt;
    &lt;param-name&gt;facelets.BUILD_BEFORE_RESTORE&lt;/param-name&gt;
    &lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p>When this initialization parameter is turned on, it changes <code>ViewHandler.restoreView()</code> to build the view before asking the <code>StateManager</code> for help.</p>
<p>However, if you are using RichFaces, for some reason this is breaking a few Ajax components! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /><br />
To be honest with you, I didn&#8217;t investigate in depth why these components don&#8217;t work with this parameter set to true.</p>
<p>What I did instead is to make sure the session actually never times out! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
To do that, I am polling the server every 29 minutes (as my session time out is set to 30 minutes). Obviously, you can poll the server only every 59 minutes if you set your session time out to 60 minutes.</p>
<p>Here is the code I used to poll the server every 29 minutes:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;h:form&gt;
    &lt;a4j:poll id=&quot;poll&quot; interval=&quot;1740000&quot; limitToList=&quot;true&quot; /&gt;
&lt;/h:form&gt;
</pre>
<p>Note that the interval attribute is in milliseconds (29 minutes x 60 x 1000 = 1,740,000 milliseconds).</p>
<p>This solution is far from being perfect! Indeed, if, for example, a user doesn&#8217;t close his browser during the night, it means that we will have to keep the session opened during hours! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_neutral.gif' alt=':|' class='wp-smiley' /><br />
But, as far as I am concerned, it is still better than to throw an exception at the user face. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2009/11/25/no-saved-view-state/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>RichFaces is too greedy</title>
		<link>http://www.logikdev.com/2009/11/17/richfaces-is-too-greedy/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=richfaces-is-too-greedy</link>
		<comments>http://www.logikdev.com/2009/11/17/richfaces-is-too-greedy/#comments</comments>
		<pubDate>Tue, 17 Nov 2009 21:33:09 +0000</pubDate>
		<dc:creator>smoreau</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[AjaxStateManager]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[COMPRESS_STATE_IN_SESSION]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[memory]]></category>
		<category><![CDATA[RichFaces]]></category>
		<category><![CDATA[state manager]]></category>

		<guid isPermaLink="false">http://www.logikdev.com/?p=18</guid>
		<description><![CDATA[For my first post, let&#8217;s talk a little bit about RichFaces. RichFaces is a very powerful JSF library which allows you to easily integrate Ajax capabilities into your website. To see all the components RichFaces has to offer, please click on the following link: http://livedemo.exadel.com/richfaces-demo/richfaces/actionparam.jsf I am now using this framework for about two years [...]]]></description>
			<content:encoded><![CDATA[<p>For my first post, let&#8217;s talk a little bit about <strong>RichFaces</strong>.</p>
<p>RichFaces is a very powerful JSF library which allows you to easily integrate Ajax capabilities into your website. To see all the components RichFaces has to offer, please click on the following link: <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/actionparam.jsf">http://livedemo.exadel.com/richfaces-demo/richfaces/actionparam.jsf</a></p>
<p>I am now using this framework for about two years and I quite like how easy it is to use! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  However, at the start, I was only using it in small projects with less than two hundred of unique visitors a day.</p>
<p>That is why I didn&#8217;t discover earlier that RichFaces was using so much memory! Indeed, I am now working on a project that has nearly 50,000 unique visitors a day. When we decided to rebuild it using JSF and RichFaces, I didn&#8217;t think that 6Gb of RAM wouldn&#8217;t be enough to keep it running! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> </p>
<p>People who knows JSF would say: &#8220;Why don&#8217;t you use &#8216;client&#8217; as state saving method?&#8221;. Well, because of the complexity of my pages, the size of these pages increases so much that it can easily reach 2Mb (which is not acceptable). So, I need to keep the view state on server side.</p>
<p>Still in JSF, there is a way of compressing the view state before saving it in session (part of the web.xml file):</p>
<pre class="brush: xml; title: ; notranslate">
&lt;context-param&gt;
    &lt;param-name&gt;org.apache.myfaces.SERIALIZE_STATE_IN_SESSION&lt;/param-name&gt;
    &lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;context-param&gt;
    &lt;param-name&gt;org.apache.myfaces.COMPRESS_STATE_IN_SESSION&lt;/param-name&gt;
    &lt;param-value&gt;true&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p>Strangely enough, the second parameter (<code>COMPRESS_STATE_IN_SESSION</code>) doesn&#8217;t work with RichFaces. After investigating the code, it seems that the RichFaces state manager (<code>org.ajax4jsf.application.AjaxStateManager</code>) doesn&#8217;t support compression at all! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>Why not? Well, I didn&#8217;t find a good reason so I decided to compress it myself. <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  The solution is to extend the AjaxStateManager and compress the view state before saving it in session and uncompress it when retrieving it from the session. Pretty easy!!! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Enough talking, here is the code of this custom state manager:</p>
<pre class="brush: java; title: ; notranslate">
package org.ajax4jsf.application;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.faces.FacesException;
import javax.faces.application.StateManager;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.render.ResponseStateManager;

import org.ajax4jsf.context.ContextInitParameters;

/**
 * Overrides the Ajax state manager to enable the state compression.
 * @author Stéphane Moreau
 */
public class MyAjaxStateManager extends AjaxStateManager {
	/**
	 * Only applicable if state saving method is &quot;server&quot; (= default) and if
	 * &lt;code&gt;org.apache.myfaces.SERIALIZE_STATE_IN_SESSION&lt;/code&gt; is
	 * &lt;code&gt;true&lt;/code&gt; (= default).
	 * If &lt;code&gt;true&lt;/code&gt; (default) the serialized state will be compressed before
	 * it is written to the session.
	 * If &lt;code&gt;false&lt;/code&gt; the state will not be compressed.
	 */
	private static final String COMPRESS_SERVER_STATE_PARAM = &quot;org.apache.myfaces.COMPRESS_STATE_IN_SESSION&quot;;

	/**
	 * Default value for &lt;code&gt;org.apache.myfaces.COMPRESS_STATE_IN_SESSION&lt;/code&gt;
	 * context parameter.
	 */
	private static final boolean DEFAULT_COMPRESS_SERVER_STATE_PARAM = true;

	private static final int UNCOMPRESSED_FLAG = 0;
	private static final int COMPRESSED_FLAG = 1;

	private final ComponentsLoader componentLoader;

	public MyAjaxStateManager(StateManager stateManager) {
		super(stateManager);
		componentLoader = new ComponentsLoaderImpl();
	}

	/**
	 * Reads the value of the &lt;code&gt;org.apache.myfaces.COMPRESS_STATE_IN_SESSION&lt;/code&gt;
	 * context parameter.
	 * @see COMPRESS_SERVER_STATE_PARAM
	 * @param context &lt;code&gt;FacesContext&lt;/code&gt; for the request we are processing.
	 * @return boolean true, if the server state steam should be compressed
	 */
	protected static boolean isCompressStateInSession(FacesContext context) {
		String value = context.getExternalContext().getInitParameter(
				COMPRESS_SERVER_STATE_PARAM);
		boolean compress = DEFAULT_COMPRESS_SERVER_STATE_PARAM;
		if (value != null) {
			compress = Boolean.valueOf(value);
		}
		return compress;
	}

	@Override
	protected Object[] buildViewState(FacesContext context) {
		Object[] viewStateArray = null;
		UIViewRoot viewRoot = context.getViewRoot();
		if (null != viewRoot &amp;&amp; !viewRoot.isTransient()) {
			TreeStructureNode treeStructure = (TreeStructureNode) getTreeStructureToSave(context);
			Object state = getComponentStateToSave(context);
			if (isSavingStateInClient(context)) {
				viewStateArray = new Object[]{treeStructure, state};
			} else {
				viewStateArray = saveStateInSession(context, treeStructure,
						handleSaveState(context, state));
			}

		}
		return viewStateArray;
	}

	@Override
	public UIViewRoot restoreView(FacesContext context, String viewId,
			String renderKitId) {
		UIViewRoot viewRoot = null;
		ResponseStateManager responseStateManager = getRenderKit(context,
				renderKitId).getResponseStateManager();
		TreeStructureNode treeStructure = null;
		Object[] state = null;
		Object[] serializedView = null;
		if (isSavingStateInClient(context)) {
			serializedView = (Object[]) responseStateManager.getState(context,
					viewId);

			if (null != serializedView) {
				treeStructure = (TreeStructureNode) serializedView[0];
				state = (Object[]) serializedView[1];
			}
		} else {
			serializedView = restoreStateFromSession(context, viewId,
					renderKitId);

			if (null != serializedView) {
				treeStructure = (TreeStructureNode) serializedView[0];
				state = (Object[]) handleRestoreState(context, serializedView[1]);
			}
		}

		if (null != treeStructure) {
			viewRoot = (UIViewRoot) treeStructure.restore(componentLoader);
			if (null != viewRoot &amp;&amp; null != state) {
				viewRoot.processRestoreState(context, state[0]);
				restoreAdditionalState(context, state[1]);
			}
		}
		return viewRoot;

	}

	private static final Object handleSaveState(FacesContext context, Object state) {
		if (ContextInitParameters.isSerializeServerState(context)) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
			ObjectOutputStream oas = null;
			try {
				OutputStream os = baos;
				if(isCompressStateInSession(context))
				{
					os.write(COMPRESSED_FLAG);
					os = new GZIPOutputStream(os, 1024);
				}
				else
				{
					os.write(UNCOMPRESSED_FLAG);
				}

				oas = new ObjectOutputStream(os);
				oas.writeObject(state);
				oas.flush();
			} catch (Exception e) {
				throw new FacesException(e);
			} finally {
				if (oas != null) {
					try {
						oas.close();
					} catch (IOException ignored) { }
				}
			}
			return baos.toByteArray();
		} else {
			return state;
		}
	}

	private static final Map&lt;String,Class&lt;?&gt;&gt; PRIMITIVE_CLASSES =
		new HashMap&lt;String,Class&lt;?&gt;&gt;(9, 1.0F);

	static {
		PRIMITIVE_CLASSES.put(&quot;boolean&quot;, boolean.class);
		PRIMITIVE_CLASSES.put(&quot;byte&quot;, byte.class);
		PRIMITIVE_CLASSES.put(&quot;char&quot;, char.class);
		PRIMITIVE_CLASSES.put(&quot;short&quot;, short.class);
		PRIMITIVE_CLASSES.put(&quot;int&quot;, int.class);
		PRIMITIVE_CLASSES.put(&quot;long&quot;, long.class);
		PRIMITIVE_CLASSES.put(&quot;float&quot;, float.class);
		PRIMITIVE_CLASSES.put(&quot;double&quot;, double.class);
		PRIMITIVE_CLASSES.put(&quot;void&quot;, void.class);
	}

	private static final Object handleRestoreState(FacesContext context, Object state) {
		if (ContextInitParameters.isSerializeServerState(context)) {
			ObjectInputStream ois = null;
			try {
				ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
                InputStream is = bais;
                if(is.read() == COMPRESSED_FLAG) {
                	is = new GZIPInputStream(is);
                }
				ois = new ObjectInputStream(is) {
					@Override
					protected Class&lt;?&gt; resolveClass(ObjectStreamClass desc)
					throws IOException, ClassNotFoundException {
						String name = desc.getName();
						try {
							return Class.forName(name, true,
									Thread.currentThread().getContextClassLoader());
						} catch (ClassNotFoundException cnfe) {
							Class&lt;?&gt; clazz = PRIMITIVE_CLASSES.get(name);
							if (clazz != null) {
								return clazz;
							} else {
								throw cnfe;
							}
						}
					}
				};
				return ois.readObject();
			} catch (Exception e) {
				throw new FacesException(e);
			} finally {
				if (ois != null) {
					try {
						ois.close();
					} catch (IOException ignored) { }
				}
			}
		} else {
			return state;
		}
	}

}
</pre>
<p>To enable it, just add the following lines in your faces config file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;application&gt;
    &lt;state-manager&gt;org.ajax4jsf.application.SearchMedicaStateManager&lt;/state-manager&gt;
&lt;/application&gt;
</pre>
<p>With this state manager, my web application is now using less than 1Gb of memory and is working perfectly fine! <img src='http://www.logikdev.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.logikdev.com/2009/11/17/richfaces-is-too-greedy/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

