Posts mit dem Label JSF werden angezeigt. Alle Posts anzeigen
Posts mit dem Label JSF werden angezeigt. Alle Posts anzeigen

Donnerstag, 29. November 2012

Weblets 1.3 released

Just a short notice, that Weblets 1.3 is released on Maven Central. To include Weblets in your own programs use following Maven directive. If you want to include Weblets in your program simply now use following entries in your dependencies section.

<dependency>
    <groupId>com.github.weblets</groupId>
    <artifactId>weblets-api</artifactId>
    <version>1.3</version>
</dependency>

and for the implementation use following include 

<dependency>
    <groupId>com.github.weblets</groupId>
    <artifactId>weblets-impl</artifactId>
    <version>1.3</version>
</dependency>

For a summary of the new features see either the Weblets documentation or following blogpost.

 

Links

[1] Weblets homepage

[2] Weblets 1.2 and 1.3 features blogpost

[2] Weblets documentation

Donnerstag, 8. November 2012

Marrying Scala with Apache MyFaces Part 4 - Apache MyFaces Extension Scripting

Introduction

In Parts 1 2 and 3 we have had a look at various implementation aspects on how to enable Scala and Apache MyFaces.
Part 4 introduces a framework which allows a zero restart configuration for Scala based JSF artifacts, such as components, managed beans, renderers etc...

This project is a relatively new extension to the Apache MyFaces project which already has had spawned several sideprojects such as CODI or Ext-Val.

The projects name is Ext-Scripting.

What is Ext-Scripting? This is an ongoing effort to integrate scripting languages into Apache MyFaces in a way that the user gets zero restart configurations for code writing.

Following video will give more details on what Ext-Scripting can provide:



Ext-Scripting itself is not only a Scala specific project but also supports as of now Groovy, dynamically recompiled Java  and soon JRuby.
One of the major aspects of Ext-Scripting was to provide extensive documentation which you can find here.

In this blog we will trim down all the information provided to give you the bare essentials in the shortest possible time.

Ext-Script in action

Ext-Script allows you now to edit direct JSF artifacts like managed beans and recompiles those artifacts on the fly. Very similar to JSP, however in JSP you were limited to stateless pages,  Ext-Scripting literally allows you to edit most JSF artifacts no matter if they are stateless or stateful.

It uses sophisticated dependency detection mechanisms on bytecode level, to reload exactly the artifacts it needs to keep the system in a stable state.

Following video (With a Java Example) will demonstrate of what happens exactly



So what does this mean for Scala. Once Ext-Scripting is enabled you can start to write managed beans, components, navigation handlers, phase listeners etc... directly in Scala and have Ext-Scripting do the heavy lifting for you.

Your server restart times will be reduced up to 90% by simply using the dynamic recompilation feature. You even can use the JSF annotations in a dynamic manner, by simply moving them deleting them etc...

Getting started -

Maven config

The easiest way to get started with Ext-Scripting is simply to take one of the example projects provided by the distribution and to start hacking or use maven. We will emphasis on the maven configuration in this blog. To add Ext-Scripting all you need is a working war configuration and then add following entries to your dependency section:

<dependency>
 <groupId>org.apache.myfaces.extensions.scripting</groupId>
 <artifactId>extscript-myfaces20-bundle</artifactId>
 <version>1.0.4</version>
</dependency>


And for the Scala support:

<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-compiler</artifactId>
    <version>2.9.1</version>
</dependency>


This should add all the needed dependencies automatically to your project.

web.xml

General Setup To have Apache MyFaces picking up Ext-Scripting we have to add following context parameter to the web.xml:

<context-param>
     <description>
         Enables our scripting engine support plugins
     </description>
     <param-name>org.apache.myfaces.FACES_INIT_PLUGINS</param-name>
     <param-value>
         org.apache.myfaces.extensions.scripting.servlet.StartupServletContextPluginChainLoader
     </param-value>
</context-param>

Setting up your source directories

Now theoretically you can start to code. Ext-Script will pick up sources hosted under WEB-INF/scala in your deployment directory. However under normal circumstances this is undesired because you want to have Ext-Scripting to pick up the sources from your real source directories for editing.

So we now have a number of context parameters in the web.xml which will allow Ext-Scripting to pick up your various sources from the source destinations itself.

For Scala following config parameters is relevant:

<context-param>
     <description>Additional comma separated loader paths to allow direct editing on the sources directory instead of the deployment dir
     </description>
     <param-name>org.apache.myfaces.extensions.scripting.scala.LOADER_PATHS</param-name>
     <param-value>
   <some project path>/src/main/webapp/WEB-INF/scala
     </param-value>
</context-param>


Now this is all to have Ext-Script to pick up your sources from the Scala path and you can start. Happy Coding.

[1] Link to Apache MyFaces Ext-Scripting
[2] Marrying JSF and Scala Part 1
[3] Marrying JSF and Scala Part 2
[4] Marrying JSF and Scala Part 3

Ext-Script and TomEE

Introduction:

I just wanted to inform everyone that Apache MyFaces Extension-Scripting works out of the box with Apache TomEE.

 

 What is Apache MyFaces Ext-Scripting?


For all people who don't know what Ext-Script is (probably most of you). Apache MyFaces Extension Scripting short Ext-Script is an Apache MyFaces extension which provides scripting language support and dynamic recompilation for Apache MyFaces. This means you can code the JSF parts of your project in Groovy, Scala, Java and soon in JRuby and you get jsp like dynamic recompilation of those parts for free.

It does not work with all app servers due to server limitations (mostly in the classloader section)  but so far it has been tested with

  • Tomcat
  • Jetty
  • Websphere Liberty Profile
  • Glassfish and
  • TomEE

More information about Apache MyFaces Ext-Scripting here.

This blogpost is about TomEE and how to get it up and running with this excellent lightweight server.

 

What is TomEE:


TomEE is a project, which provides a full JEE Web Profile to a Tomcat, it does not touch Tomcat but provides the entire JEE web profile stack (and more) within a standard Tomcat war container.  Thats right no EAR anymore just drop a war and you will get JSF CDI etc... out of the box from the container.
More information on Apache TomEE here. No more bundling of JSF CDI etc... all is provided by a lightweight servlet container with great startup times.

 

Combination of both


So how do we combine both containers? The answer is simple, drop
Ext-Scripting:

  • extscript-myfaces20-bundle-1.0.4.jar

and its dependencies :

  • commons-beanutils.jar version 1.8.3 or above
  • commons-codec.jar version 1.3 or above
  • commons-collections.jar version 3.2 or above
  • commons-io.jar version 1.4 or above
  • groovy-all.jar version 1.7.2 or above
  • scala-compiler.jar version 2.10.0-M2 or above
  • scala-library.jar version 2.10.0-M2 or above

(Note if you use Maven then Maven will do the job for you) into your war WEB-INF/LIB and set following configuration entries:

<context-param>
        <description>
            Initializes the plugins for our groovy handlers
        </description>
        <param-name>org.apache.myfaces.FACES_INIT_PLUGINS</param-name>
        <param-value> 
            org.apache.myfaces.extensions.scripting.jsf.startup.StartupServletContextPluginChainLoader
        </param-value>
</context-param>


This is the most important entry and under normal Servlet containers now we would be set and could start coding, however we have to set additional parameters for TomEE:

 <context-param>
        <description>Additional comma separated loader paths to allow direct editing on the sources directory instead
            of the deployment dir
        </description>
        <param-name>org.apache.myfaces.extensions.scripting.groovy.LOADER_PATHS</param-name>
        <param-value>
            /whatever/myfaces20-extscript-helloworld/src/main/webapp/WEB-INF/groovy
        </param-value>
</context-param>

<context-param>
        <description>Additional comma separated loader paths to allow direct editing on the sources directory instead
            of the deployment dir
        </description>
        <param-name>org.apache.myfaces.extensions.scripting.java.LOADER_PATHS</param-name>
        <param-value>
            /whatever/myfaces20-extscript-helloworld/src/main/webapp/WEB-INF/java
        </param-value>
</context-param>
    
<context-param>
        <description>Additional comma separated loader paths to allow direct editing on the sources directory instead
            of the deployment dir
        </description>
        <param-name>org.apache.myfaces.extensions.scripting.scala.LOADER_PATHS</param-name>
        <param-value>
            /whatever/myfaces20-extscript-helloworld/src/main/webapp/WEB-INF/scala
        </param-value>
</context-param>

<context-param>
        <description>Additional comma separated loader paths to allow direct editing on the source
        directories of the deployment dir.
        </description>
        <param-name>org.apache.myfaces.extensions.scripting.ruby.LOADER_PATHS</param-name>
        <param-value>
            /whatever/extscript-examples/myfaces20-example/src/main/webapp/WEB-INF/ruby
        </param-value>
</context-param>


Those paths point to your source directories hosting the source files. (Note that the Ruby loader paths are only valid with the latest 1.0.5-SNAPSHOTS, 1.0.4 has no Ruby support)

Once done you can start coding in the code hosted at the respective directories.

 More information about setting up Ext-Script can be found here.

Dienstag, 28. Februar 2012

 Marrying JSF and Scala part 3: Custom Components in Scala

Introduction

While JSF2.0 has simlified the component building a lot thanks to the
composite components, there are still usecases when the classical component
building tasks have to be performed.

We showed in part 1 and part 2 how to build the basic JSF artifacts in Scala we now dive deeper into
JSF by showing how to leverage Scala to build your own jsf custom component.

With this article we combine various techniques of Scala for programming custom components.
The case we are going to investigate is a simple hello world component.

A custom component in Scala

First we have a look at the component itself:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import javax.faces.component.{UINamingContainer, FacesComponent}
import java.util.logging.Logger
import javax.faces.event._


/**
 *
 * @author Werner Punz (latest modification by $Author$)
 * @version $Revision$ $Date$
 */

object HelloWorld {
    /*attributes*/
    val ID = "id"
    val SAY_HELLO = "sayHello"

    /*statics*/
    val logger = Logger.getLogger("HelloWorld")
}


/**
 * helper to avoid a problem with the image button being nested in another component
 * takes a calendar as value
 */
@FacesComponent("at.irian.HelloWorld")
@serializable
@ListenersFor(Array(
    new ListenerFor(systemEventClass = classOf[PostRestoreStateEvent]),
    new ListenerFor(systemEventClass = classOf[PostAddToViewEvent])
))
class HelloWorld extends UINamingContainer with StandardComponent {
    /*lets import the attributes due to not having java structs*/

    import HelloWorld._

    def setSayHello2(hello: String) {
        setAttr[String](SAY_HELLO, hello)
    }

    def getSayHello2(): String = getAttr[String](SAY_HELLO, "") + " added text"

    //we now handle the special events
    override def processEvent(event: ComponentSystemEvent) {
        event match {
            case evt: PostAddToViewEvent => logger.info("PostAddToViewEvent called"+getAttr[String](SAY_HELLO,""))
            case evt: PostRestoreStateEvent => logger.info("PostRestoreStateEvent called")
            case _ => {}
        }

        super.processEvent(event)
    }
}
Code a) Custom component

We have a simple component which exposes one additional attribute sayHello2. The component itself is a composite component with an xml template for rendering an performs some listener tasks.

So far so good, however we use several things here which are of interest:

1
2
3
4
5
6
7
8
object HelloWorld {
    /*attributes*/
    val ID = "id"
    val SAY_HELLO = "sayHello"

    /*statics*/
    val logger = Logger.getLogger("HelloWorld")
}
Code b) Singleton
  • A singleton object for static replacements and struct replacements
1
@ListenersFor(Array(...
Code c) Listeners Array
  • A listeners array for combining multiple listeners 
1
with StandardComponent
Code d) trait 
  • a trait instead of a utils class to combine common functionality of components 
1
2
3
4
5
 event match {
            case evt: PostAddToViewEvent => logger.info("PostAddToViewEvent called"+getAttr[String](SAY_HELLO,""))
            case evt: PostRestoreStateEvent => logger.info("PostRestoreStateEvent called")
            case _ => {}
        }
Code e) Type matches
  • matches for types to avoid instanceof cascades
Lets dissect the code parts one by one:


1) Object HelloWorld

Scala does not have neither static variables nor structs, instead of that it provides singletons as language construct.
Static variables simply can be simulated by a singleton and a simple in class import:

1
2
3
4
5
6
7
8
object HelloWorld {
    /*attributes*/
    val ID = "id"
    val SAY_HELLO = "sayHello"

    /*statics*/
    val logger = Logger.getLogger("HelloWorld")
}
Code b) Singleton 

 and then

1
 import HelloWorld._  
 Code f) import

Allows you to import the instance variables and methods as semi native members.

1
logger.info("PostAddToViewEvent called"+getAttr[String](SAY_HELLO,""))
 Code g) import usage

2) Annotation Arrays

1
2
3
4
@ListenersFor(Array(
    new ListenerFor(systemEventClass = classOf[PostRestoreStateEvent]),
    new ListenerFor(systemEventClass = classOf[PostAddToViewEvent])
))
 Code h) annotation array Scala

is simply what would be in Java
1
2
3
4
@ListenersFor({
   @ListenerFor(systemEventClass = classOf[PostRestoreStateEvent]),
   @ListenerFor(systemEventClass = classOf[PostAddToViewEvent])
})
 Code i) annotation array Java

Since this code transition is not quite obvious even within the Scala documentation, it is worth to be noted in this blog.

3) Traits

The most interesting part is the traits part.
First of all, what is a trait. To sum it up, a trait is an abstract class which can be multiply inherited sort of an interface
with code. Now this opens quite a few possibilities.
Common constraints can be isolated and shared among object instances without having to revert to singletons.
Traits can access "this" and can call methods provided by the class as abstract members.

We reuse traits in this case to isolate common component behavior without having to introduce yet another helper class or an
abstract base class. In fact we finally can share this referencing code among components with different base classes without having to introduce our own inheritance hierarchy.

The trait looks like following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
trait StandardComponent {


    def getViewRoot = FacesContext.getCurrentInstance.getViewRoot

    def getLocale: Locale = FacesContext.getCurrentInstance.getViewRoot.getLocale

    def getAttr[T](key: Serializable, default: T): T = {
        val ret = getAttributes().get(key)
        if (ret != null) ret.asInstanceOf[T] else default
    }

    def setAttr[T](key: String, value: T) {
        //note the scala compiler compiles anyref to java.lang.Object
        //in scala itself anyref is one level above Any which is the base
        //of everything scalawise
        getAttributes.put(key, value.asInstanceOf[AnyRef])
    }

    def getAttributes(): java.util.Map[String, AnyRef]

    def reqAttrMap: java.util.Map[String, String] = {
        FacesContext.getCurrentInstance.getExternalContext.getRequestParameterMap
    }


    def getReqAttr(key: String): String = {
        reqAttrMap.get(key)
    }
}
 Code j) Trait

We use only a subset of this functionality namely getAttr and setAttr.




1
2
3
4
   def getAttr[T](key: Serializable, default: T): T = {
       val ret = getAttributes().get(key)
       if (ret != null) ret.asInstanceOf[T] else default
   }
 Code k) getAttr

Here we can see clearly the this reference to the underlying component getAttributes with
 
def getAttributes(): java.util.Map[String, AnyRef]
 
being defined only as interface, which has to be implemented by the component or one of its parents.

4) Match patterns

Now an interesting language part in Scala is the extended matches. Not only you can match in Scala for values, also matches for types and patterns are allowed.
We use the type matches to avoid instanceof if cascades:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//we now handle the special events
override def processEvent(event: ComponentSystemEvent) {
    event match {
        case evt: PostAddToViewEvent => logger.info("PostAddToViewEvent called"+getAttr[String](SAY_HELLO,""))
        case evt: PostRestoreStateEvent => logger.info("PostRestoreStateEvent called")
        case _ => {}
    }

    super.processEvent(event)
}
 Code l) match patterns

The cases basically replace if instanceof constructs here


 A renderer in Scala

Now what if we want to write the renderer in Scala.
Scala there can support us as well, it has XML support in the language baked in.
Now lets have a look at the renderer (if not done in an xhtml template like it should be)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import javax.faces.render.{Renderer, FacesRenderer}
import javax.faces.context.FacesContext
import javax.faces.component.UIComponent

@FacesRenderer(componentFamily = "javax.faces.Output", rendererType = "at.irian.HelloWorld")
class HelloWorldRenderer extends Renderer {
    override def encodeEnd(context: FacesContext, component: UIComponent) {

        val responseWriter = context.getResponseWriter,
        val text = component.asInstanceOf[HelloWorld].getSayHello2(),
        val id = component.getClientId

        responseWriter.write(
                <div class="helloWorld" layout="block" id={id}>
                    {text}
                </div>.toString
        )
    }
}
 Code m) renderer

Now the interesting part of this renderer is following code:
1
2
3
4
5
     responseWriter.write(
                <div class="helloWorld" layout="block" id={id}>
                    {text}
                </div>.toString
            )
 Code m) render part

As we can see, we simply write the html directly constructs like     id={id} and {text} allow for inline templating.

There are constraints to this approach
  • We cannot write out partial xml. The xml written always must be complete, hence we cannot simply write an open tag first, call a subclass and then close the tag
  • We do not use the startElement, endElement. The plus side is readability. 
  • In the end a composite component and its direct xhtml rendering should always be the first choice. Xhtml simply is the target platform in most cases why not use xhtml also for the component renderer part.

References
  1. Marrying JSF and Scala Part1
  2. Marrying JSF and Scala Part2
  3. Custom Components in JSF (German)
  4. Scala Documentation

Freitag, 25. November 2011

JSF Ajax and Multiple Forms

This blogpost is about a problem which about 80% of all user problems regarding JSF Ajax in the myfaces mailinglist revolve around. Namely how do I handle the jsf ajax in a multiple form scenario.

JSF Ajax and multiple forms, a standard case, which should be easy right.
Let's have a small look at an example:

<h:form id="firstForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget1"/>
<h:inputText id="first_input" value="#{multiFormBean.inputText1}"/>
<h:commandButton action="#{multiFormBean.doSubmit1}" value="submit1"
onclick="javascript:jsf.ajax.request(this, event, {execute:'firstForm', render:'renderTarget1'}); return false;">
</h:commandButton>
</h:form>
<h:form id="secondForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget2"/>
<h:inputText id="second_input" value="#{multiFormBean.inputText2}"/>
<h:commandButton action="#{multiFormBean.doSubmit2}" value="submit2"
onclick="javascript:jsf.ajax.request(this, event, {execute:'firstForm', render:'renderTarget2'}); return false;">
</h:commandButton>
</h:form>
view raw multiform.xhtml hosted with ❤ by GitHub


As we see here, two forms each updating a component in itself via ajax.
Now what happens if we submit the forms alternating.

After a while we run into a ViewRoot cannot be found Exception on the server side.

We did everything right, why do we face this issue?

The answer lies in a bug in the JSF Ajax protocol, more precisely the way the ViewState is processed.

Lets have a look at an Ajax response:

<?xml version="1.0" encoding="utf-8"?>
<partial-response>
<changes>
<update id="renderTarget1"><![CDATA[<div id="renderTarget1"></div>]]></update>
<update id="javax.faces.ViewState">
<![CDATA[T2Sk3fhPxh/3V4FRMOA6jXjkc/Z9bOAzqA4dBeXHVrNpgC/cMgAi7bRUgL/faSQmOhYwkpPoG/cv8YZeyNlxa6B0r81ssbeWnBWZ5g7NG4K8Tt+E87ihH1XErK0AUsYTw8zKRDKGFrj7IKs25F3zdhmy6WV1EaSSIxyD5w==]]></update>
</changes>
</partial-response>
view raw response.xml hosted with ❤ by GitHub


Here we see the root cause of the problem. There is a parameter defining the ViewState with the identifier javax.faces.ViewState, however it is not clear where it belongs to.

Practically a viewstate must be attached to a form. So the issuing form definitely must receive it. However what about the other forms?

And here is the root cause of the error. Only the issuing form is updated and the ViewState which is dependend on the viewroot not the form in the second form is not updated.

This image shows exactly what happens:


As you can see only one form is update the second form now has a viewstate which is not the current one and at one point is dropped from the ViewState history, a classical concurrency issue.

So the solution would be to update all forms in the html document, right?

Theoretically yes, but there is one API which prevents this simple solution. Portlets.
In a portlet environment you have multiple viewroots all belonging to different jsf session instances on the server.


The next logic solution would be to update all jsf elements under ViewRoot.

Again, a good idea, but the protocol prevents it. On the pure client side we do not have any marker or indicator, which tells the ajax code where the current ViewRoot begins.

To ease this protocol problem an extension to the jsf spec was added under 2.1 which eases this problem. According to the spec you have to add the second form manually as render target. Something which both implementations follow. Here is a snippet which shows the solution:

<h:form id="firstForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget1"/>
<h:inputText id="first_input" value="#{multiFormBean.inputText1}"/>
<h:commandButton action="#{multiFormBean.doSubmit1}" value="submit1"
onclick="javascript:jsf.ajax.request(this, event, {execute:'firstForm', render:'renderTarget1 secondForm'}); return false;">
</h:commandButton>
</h:form>
<h:form id="secondForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget2"/>
<h:inputText id="second_input" value="#{multiFormBean.inputText2}"/>
<h:commandButton action="#{multiFormBean.doSubmit2}" value="submit2"
onclick="javascript:jsf.ajax.request(this, event, {execute:'firstForm', render:'renderTarget2 firstForm'}); return false;">
</h:commandButton>
</h:form>


Here we can see, we have added the second form as render target.

Now both forms will be updated and the viewstate always will be up to date.


This solution while being spec compliant is not satisfactory. Sometimes you dont know if a certain form is still present after the ajax case. Is there still a way to update all forms in the page or at least to take the form id out of the equation?

Unfortunately not within the bounds of the specification. However, being aware of this issue, I have added in Apache MyFaces additionally to the spec behavior two other ways to resolve the issue.

First, you don't have to define the form as render target, but you can define any element within a form as render target and the form will be updated.

<h:form id="firstForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget1"/>
<h:inputText id="first_input" value="#{multiFormBean.inputText1}"/>
<h:commandButton action="#{multiFormBean.doSubmit1}" value="submit1"
onclick="javascript:jsf.ajax.request(this, event, {execute:'firstForm', render:'renderTarget1 renderTarget2'}); return false;">
</h:commandButton>
</h:form>
<h:form id="secondForm" prependId="false">
<h:panelGroup layout="block" id="renderTarget2"/>
<h:inputText id="second_input" value="#{multiFormBean.inputText2}"/>
<h:commandButton action="#{multiFormBean.doSubmit2}" value="submit2"
onclick="javascript:jsf.ajax.request(this, event {execute:'firstForm', render:'renderTarget1 renderTarget2'}); return false;">
</h:commandButton>


Secondly, the probably best solution. A configuration parameter which forces MyFaces to update all forms in a page.

With following code snippet you can enable this mechanism:
window.myfaces = window.myfaces || {};
myfaces.config = myfaces.config || {};
//set the config part
myfaces.config.no_portlet_env = true;
view raw noportlet.js hosted with ❤ by GitHub


Once you have added this snippet of javascript, myfaces will be in no portlet mode and will enforce an update all forms with the viewstates policy.

Note: While this method wont break the code if you switch to mojarra, you will not get the benefits, because Mojarra does not yet have a similar solution to the issue.

Donnerstag, 24. November 2011

JSF Ajax Encoding

The entire story started when we got the request to encode everything in ISO-8859-51 including the ajax cycle. Well first I thought it was easy just change the encoding on the javascript side, let the server handle the rest. The encoding was easily detectable on the javascript side simply by checking the xhtmls encoding (the meta tag head encoding itself would have been another option, but since we are nailed down to xhtml anyway due to facelets we have an easier way)
Easy, I thought, but then I ran into browser hell.

The problem normally would be easily resolvable. The XHR object has the option of adding
xhr header content type:

xhr.setRequestHeader("ContentType", "application/x-www-form-urlencoded; charset=ISO-8859-15");

The problem now are the browsers themselves. By testing the dynamic encoding on various browsers following came out:

BrowserActual Encoding
Mozilla 7UTF-8
Chrome UTF-8
IE ISO-8859-15
Opera ISO-8859-15


So what does this mean, only opera and IE got it right. Which means the path of allowing non UTF-8 submits is blocked for now.

However JSF automatically deals with the problem properly. While I implemented the most of the Ajax part of myfaces, I have to admit the actual encoding part was provided by another project, namely j4fry and its implementors worked on that part, so I never gave a second thought. However both implementations deal the same way with the issue.

First ajax submits are UTF-8 encoded, this at the first look could pose problems with non UTF pages. It turns out there are none.

The solution both implementations follow is to encode the actual key value pair parameters into a utf url encoded representation.

Both implementations seem to apply the encodeURIComponent function of javascript-
Now now matter what content type the page has, always a proper utf-8 representation of the original content will be passed down.

Given the response type also then is UTF-8 what happens with the response. After all the page needs to handle the response properly in its own encoding.
Well there MyFaces and Mojarra differ slightly. Both in compliance with the spec, encode the response in a XML CDATA block. However MyFaces does additional escaping of non ascii chars with their unicode representation, while Mojarra simply pushes the content byte per byte into the CDATA block.


Here is an example:

Mojarra:

<?xml version='1.0' encoding='UTF-8'?>
<partial-response>
<changes>
<update id="testform"><![CDATA[
<form id="testform"
name="testform" method="post"
action="/experimental/iso-8859-15.jsf"
enctype="application/x-www-form-urlencoded">
<input type="hidden" name="testform" value="testform" />
Press fast for a delay
<input id="testform:inputtext"
type="text" name="testform:inputtext"
value="€€€€€€" />
<span id="testform:outputtext">€€€€€€</span>
<span id="testform:output">Blörks 6 zahl über...$%</span>
<a id="testform:pressme" href="#"
onclick="mojarra.ab(this,event,'action','@this testform:inputtext testform:pressme','testform');return false">
Über Pressen</a>
</form>]]></update>
<update id="javax.faces.ViewState"><![CDATA[-3413056635477888908:-884780313822768314]]></update>
</changes>
</partial-response>


Here it is clearly visible that the cdata block has a different encoding than the outer UTF-8 encoded xml. In the final page representation all the special chars are visible again as they should be.

However MyFaces goes one step further and escapes the content additionally to get rid of the non utf-8 representation of the characters.

<?xml version="1.0" encoding="utf-8"?>
<partial-response>
<changes>
<update id="testform"><![CDATA[
<form id="testform" name="testform"
method="post" action="/experimental/iso-8859-15.jsf"
enctype="application/x-www-form-urlencoded">
Press fast for a delay
<input id="testform:inputtext"
name="testform:inputtext"
type="text" value="&euro;&euro;&euro;&euro;&euro;" />
<span id="testform:outputtext">&euro;&euro;&euro;&euro;&euro;</span>
<span id="testform:output">Bl&ouml;rks 33 zahl &uuml;ber...$%</span>
<a href="#"
onclick="jsf.util.chain(document.getElementById('testform:pressme'), event,'jsf.ajax.request(\'testform:pressme\',event,{execute:\'@this testform:inputtext testform:pressme\',render:\'testform\',\'javax.faces.behavior.event\':\'action\'})'); return false;"
id="testform:pressme" name="testform:pressme">&Uuml;ber Pressen</a>
<input type="hidden" name="testform_SUBMIT" value="1" /></form>]]>
</update>
<update id="javax.faces.ViewState">
<![CDATA[X4esYFadbDOTm2+eJEayTfM3M/7uX1jS5+ZVXaklBMszHBFWKU4GwDucc84o8baxZJzgvTk8yLtX6ptwas+25gXNr8ivBBplW4WUOPqc0q87kwchVx50nD0YDYZKVUndUQ3X+09LD6e0YRrTgmBa4EMJkro=]]></update>
</changes>
</partial-response>


However this comes from the fact that myfaces basically also does an escape of special chars at a full page refresh, so the core behavior regarding the partial response is the same.

So what happens for instance if you just tamper with the UTF header.
You automatically will run into problems due to the uri encoded UTF-8 representation of the parameters. In the worst case you will trigger a server error because of non decodable parameters, in the best case if you pass down ascii only chars you will get it through, in the normal case you will get junk in which is wrongly decoded.

See here an example on IE9 and Mojarra:




The question remains, are both save from a client point of view? Theoretically it should be since everything is embedded in a CDATA block.
However I cannot say if the browsers swallow really everything within their browser engines which is embedded in a CDATA block (aka every byte combination outside of their encoding).


It comes down again to the golden rule #1 in web programming, use UFT-8 and never bother with other encodings, if you can. If you have to, be prepared to enter the valley of tears, after all UTF-8 now has been for almost a decade the fix for all the encoding issues in the web space.

Dienstag, 8. November 2011

Introducing the MyFaces jsf.js Modular Includes

Introduction:

Why modular jsf.js includes, there is one jsf.js file, right?

Since the beginning of the introduction of jsf.js in JSF there has been only one jsf.js file which serves all Ajax needs.
However, at least for Apache MyFaces there have been a lot of extensions added such as:
  • iframe ajax fileupload
  • html5 form detection
  • client side i18n message support for various languages (including chinese)
  • legacy browser support down to blackberry 4.7 and winmobile 6.5 and ie6
  • browser optimisations for browsers supporting dom level3
  • queue control for the ajax request queue
  • timeout handling
  • better error handling
  • delay handling
  • modular structure which can be changed at runtime to replace it with your own  implementation of subparts
  • clear distinction between api and impl on codelevel
(More info on many of those extended features see following Link)

Most of those extensions will make it one way or the other into the official jsf spec. However different scenarii have different needs.
While most legacy mobile browsers are now slowly phased out (and is seen as deprecated) ie6 for the time being is still supported with a burden of legacy code.
However in a pure modern mobile environment for instance you need smaller files and no legacy code at all. Many users are also perfectly happy with a pure implementation of jsf.js according to the spec without any extra features. Other users only need a subset of those features and want to leave out the other (i18n support for instance)

The advantage of dropping code is smaller filesizes, faster code due to less lines which have to be processed and less fallbacks which have to be prechecked. Something worthwhile to explore given modern mobile browser environments and situations where you simply want to be as lean as possible.

So what is the solution for all this

The MyFaces jsf.js Modular Includes

As of MyFaces 2.1.4 a modular include system will be added. Simply by adding following parameter to your web.xml you will be able to determine what will be included

<context-param>
<param-name>org.apache.myfaces.JSF_JS_MODE</param-name>
<param-value>normal</param-value>
</context-param>
<!--
node modular jsf.js includes are only enabled in production
in development the normal jsf.js is included always
-->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>

With the parameter

org.apache.myfaces.JSF_JS_MODE

and the allowed values of
  • normal
  • modern
  • minimal-modern
you will be able to adjust which version of jsf.js is included. If you need extra functionality you can include the subparts excluded from your version as separate Javascript resources via normal jsf mechanisms.

Following image shows the version of each file and the extra functionality:

Modular include parts

As you you can see you can stack and mix all the modules you need by simply choosing a base jsf.js and then you are able to stack the extra functionality needed by adding a separate include.

That way you have the choice between filesize, number of includes and features according to your needs.













Example on how to Enable the Modular Includes with Additional Features

The following example will include the minimal-modern jsf.js and will stack all the extra functionality on top of it.

web.xml

<context-param>
<param-name>org.apache.myfaces.JSF_JS_MODE</param-name>
<param-value>minimal-modern</param-value>
</context-param>
<!--
node modular jsf.js includes are only enabled in production
in development the normal jsf.js is included always
-->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>
view raw web.xml hosted with ❤ by GitHub


in your page template

<h:outputScript name="jsf.js" library="javax.faces" target="head" />
<h:outputScript name="jsf-i18n.js" library="myfaces" target="head" />
<h:outputScript name="jsf-legacy.js" library="myfaces" target="head" />
<h:outputScript name="jsf-experimental.js" library="myfaces" target="head" />
view raw includes.xhtml hosted with ❤ by GitHub


As you can see all you need to to is to reference the correct js file additionally which is hosted under the resource module myfaces and you are ready to go.