Firefox Tops 20% Market Share

December 4th, 2008

For the first time since the early days before the departure of Netscape, a competing browser to Microsoft Internet Explorer has reached and exceeded 20% market share. Firefox (www.getfirefox.com) has managed to achieve a 20.78% market share reducing Internet Explorer to 69.77% (Market Share). This is a huge achievement in the browser market share battle. Further, Internet Explorer 6 has fallen to just 21.53%. As the market share continues to fall for Internet Explorer and rise for other standards-based competing browsers (Firefox, Safari, Chrome, Opera, etc), it results in a greater push to force IE to adopt newer web standards. Newer standards supported across all major vendors means better development and improved user experiences.

If you have not tried Firefox, go download it and inform all your friends! Let’s continue to push Firefox towards 25% share and beyond!

JSTL with JSF/Facelets

October 18th, 2008

In my years of JSF development, especially with respect to Facelets, I have come to both love and hate JSTL. JSTL without Facelets is even more of a nightmare and I would strongly recommend considering otherwise. JSTL with Facelets is a little better, but still requires a full understanding of how Facelets interacts with JSF and JSTL. Without a full understanding, you will most definitely run into unforeseen issues.

First, let’s quickly review the JSF lifecycle. First, restore view will restore a saved UIViewRoot from a postback request. Second, it will apply the request parameters to the input components, perform conversions and validations, update the backing model with the converted values, and invoke actions and listeners accordingly. Finally, it will render the requested view or outcome view.

Now let’s look at Facelets. Facelets defines two different lifecycles: the compile lifecycle and the JSF lifecycle. The compile lifecycle is used to compile a given Facelet and then apply the Facelet to a UIViewRoot in order to construct the component tree. The JSF lifecycle is then activated using the built component tree from the Facelets. Technically the compile phase in Facelets is either part of the restore view phase or the render phase (depending on the facelets configuration and request type). Either way, the compile time phase happens completely before invoking the remainder of the JSF phase. Thus, it is more or less completely independent of each other. The sole purpose of the compile phase is to build the component tree from the Facelet tags. This is similar to how a JSP tag handler creates a UIComponent and adds to the component tree. However, whereas JSP is completely independent of JSF, Facelets is built very well into JSF.

So, why are these phases important? They are because Facelet tags are either TagHandlers (compile-time invocations) or ComponentHandlers (JSF invocations). ComponentHandlers are used to create a UIComponent from the tag and add to the JSF component tree. As a result, the created component is processed as part of the JSF lifecycle (validations, rendering, etc). However, TagHandlers are processed during the compile time phase and do not create components. They merely process some logic that may affect how other handlers get processed. However, they are processed before the JSF rendering lifecycle, which has some big repercussions as I will discuss later.

So what does this have to do with JSTL? Facelets implements JSTL using TagHandlers (yes, Facelets does…it does not use the standard JSTL library which is purely JSP based, not JSF). Thus, every JSTL tag is processed at compile time, not at render time within the JSF lifecycle. This means you need to know how each of the tags operates and how it impacts the component tree. After all, the primary purpose of tag handlers is to affect or build the component tree. It does not have any part in the JSF rendering phase.

For example, the c:if tag is used to apply children handlers when its expression evaluates to true. This means that the expression MUST be able to be evaluated before the restoring or rendering phases. Typically this is not an issue as expressions are available at all lifecycles as they are bound to managed beans and backing beans. The case where this breaks down is when you have components creating variable expressions during the rendering phase. An example of this is the commonly used “var” expression within the h:dataTable. The “var” expression is only valid when rows are being rendered by the data table. Because the if tag is processed before the rendering phase, its expressions would never properly evaluate. This example would always cause unexpected results:


<h:dataTable var="row" value="#{MyBean.data}">
<h:column>
<c:if test="#{row.valid}">
Hello: #{row.name}
</c:if>
</h:column>
&lt/h:dataTable>

You can see how this can be confusing, especially for new developers. If you do not understand the two lifecycles between JSTL and JSF/Facelets, you could spend hours trying to figure out why your data table is not generating content accordingly.

Let’s look at some other examples. One of my favorites is the c:forEach tag. This tag processes a given set of children tags for each iteration. This would seem to mimic the behavior of the dataTable tag. However, the two are very much different. The forEach tag is processed during the compile time phase while the dataTable is processed within the JSF lifecycle. So, why does that matter? Apart from the expressions having to be available as I already discussed, it matters severely to the component tree and memory/performance utilization. When the forEach tag is processed/applied, it applies each of its children for every iteration provided. This means that if the children tag handlers created component instances, then they would create X instances where X is the number of iterations. Let’s look at an example:


<c:forEach var="row" items="#{MyBean.data}">
&lth:outputText value="#{row.name}" />
</c:forEach>

If the MyBean.data expression resulted in 100 values, then you would have 100 HtmlOutputText components in the tree. However, if you used an h:dataTable tag, then you would only have 2 components in the tree. That does not seem all that bad. However, imagine the case where you have a large data set (ie: thousands of rows) and you had several children components. That would result in tens of thousands of components. After serializing all of those components to the state, your state will be thousands of times larger (megabytes rather than kilobytes). This can cause long access times, long download times, etc. Again, not understanding how JSTL interacts with its different phases, can quickly kill an application with unexpected results.

Now that I have showed how JSTL can be bad, let me provide one case where JSTL is very powerful (however, confusing at the same time to newbies). Let’s look at the h:panelGrid component. This component has a “columns” attribute that defines how many columns (ie: td) to create. Each child will represent one of those columns. However, imagine you want to use a panel grid but the column components you want are based on a data list that you would want to iterate over or are based on the same data that you want to avoid typing over and over (for maintenance reasons). Using panel grid with data table will not work as you would only have a single component child (the data table). Howver, let’s look at what forEach did to our component tree: it created a component instance for every child. Thus, we get a proper handling in the panel grid. For example:


<h:panelGrid columns="3">
<c:forEach var="index" start="1" end="6">
<h:panelGroup>
Index: #{index}
</h:panelGroup>
</c:forEach>
</h:panelGrid>

In looking at this you would think that it would fail because you only have a single child when you expect 3 columns. When you understand JSTL within Facelets, you realize the power and how it actually creates a 3×2 grid numbered from Index 1 to Index 6. This is because the end component tree has 6 panel group components as immediate children of the panel grid. Therefore, the panel grid is able to iterate over those panel group components accordingly.

The big point to remember to all of this is understand, understand, and understand the different lifecycles and their impact on each other. Without the understanding, you can quickly become confused on why things are not working as expected. First and foremost, understand how the JSF component tree is impacted and second how EL expressions are evaluated (especially with respect to c:set). A good suggestions is to use the ui:debug tag in Facelets and examine the output component tree to see how it is impacted after compiling/evaluating a Facelet.

CSS Sprites

October 18th, 2008

I decided to take the plunge and begin making my site more YSlow compliant. I had already enabled GZip through a custom GZip filter and browser caching for static resources. My next task was to limit the number of resources being served. My first part here was first minifying and combining all javascript and CSS resources. This reduced the number of requests to two for these types of resources. Next was background images. The best way to do this is by using sprites. A sprite is an image that includes one or more other images. CSS is then used to provide offsets into the sprite where the image is actually defined. As a result, you only need a couple of images rather than many. Within my site, this makes a drastic improvement with all the unique background images I use.

I decided to look for an automated tool to convert my CSS and background images automatically. In my findings I came across the utility SmartSprites. This utility uses CSS comments to annotate the CSS file with information about how to create the sprites. Once completed, it processes the CSS file and all images and creates an updated CSS file and sprite images. The CSS updates include the proper background-position attributes that declare the associated offsets. All in all, it was a very useful tool that I highly recommend. It got my images from 15+ to 3 without the hassle of manually creating the sprites.

In using the tool however, I had a couple of issues (which is more of my ignorance for not reading the documentation :) Anyways, here are some helpful tips and advice.

First, the tool uses Ant to launch the process. However, not enough memory wasallocated to the JVM which caused OutOfMemory errors for me. Note that not everyone will need to handle this step. Unfortunately I took several images on my site into one large sprite, so I needed the extra memory. To resolve the memory issues, I merely provided Ant more memory (-Xmx1g) to ensure I had plenty. I did this by creating an antrc_pre.bat file in my home directory with the line:

SET ANT_OPTS=-Xmx1g

Once I had enough memory, I was now ready to start annotating. The first thing I did was define the sprite references at the top of the CSS file. The sprite references allow you to use multiple sprites in the same file. Note that the examples below appear to wrap the lines. Unfortunately that is an issue with the blog software. All examples below should be on a single line in the CSS without wrapping.


/** sprite: sprite; sprite-image: url('../images/sprite.png'); sprite-layout: vertical */

The sprite-layout defines which way to layout images within the sprite. For standard images, this is not important. However, for images with background-repeat, it is very important as CSS and browsers use the image to repetitively show the image over and over. If using the wrong layout, you will get very unexpected results. The best thing to do here is to use three sprites: one for non-repeating images, one for repeat-y based images, and a third for repeat-x images. For example:


/** sprite: sprite; sprite-image: url('../images/sprite.png'); sprite-layout: vertical */
/** sprite: repeatx; sprite-image: url('../images/sprite-horizontal.png'); sprite-layout: vertical */
/** sprite: repeaty; sprite-image: url('../images/sprite-vertical.png'); sprite-layout: horizontal */

Again, make sure those examples are on three separate lines without wrapping. Now that we have our sprites defined, we can being applying to CSS classes. The proper way to do this is to apply a comment after the associated background-image line. You will use the proper sprite reference depending on the type of background repetition.

If using a non-repeating image, use the following example:


.css-class
{
background-image: url('../images/image.jpg'); /** sprite-ref: sprite; */
background-repeat: no-repeat;
}

This example uses a relative path (highly suggested if not required) to obtain the image. In my setup I used a directory structure such as:

build
+ styles
- style.css
+ images
- image.gif

If using repeating images, use one of the following examples:


.repeat-x
{
background-image: url('../images/image.jpg'); /** sprite-ref: sprite; sprite-alignment: repeat; */
background-repeat: repeat-x;
}
.css-class
{

background-image: url(’../images/image.jpg’); /** sprite-ref: sprite; sprite-alignment: repeat; */
background-repeat: repeat-y;
}

Again, verify that the comments are on the same line as the background image without wrapping. With each image properly annotated, we can now build our updated stylesheet and sprites. To do so, just execute the ant process command (make sure to update the build.properties file first). If everything goes according to plan, you should now have new sprite images and stylesheets that you can use in your layouts.

Here are some things to consider before annotating images. If the image is only used on one or a few pages (such as titles, headers, etc), consider not annotating these images unless very small. If the images are large in size, you will end up with a very large sprite which will reduce performance. In such a case you are better off just having those few pages use another image that will be cached.

JSF Performance Improvements: Part I

October 18th, 2008

This is my first post on improving sites utilizing JSF. This post is more relevant for mostly static content that only changes at the result of database updates. One of the easiest ways to improve performance is through caching. There are several types of caching from database caching (JPA/Hibernate), model caching (EHCache), browser caching (resources, images, etc). The method I will discuss is creating a page cache within JSF. Note that this useful only when using a standard server and do not have access to higher end equipment such as routers that can automatically provide a page caching layer. If that equipment is available, those layers should always be used as they are built for that purpose. However, for simple sites looking for millisecond access times, this can be a pretty easy implementation.

To start, a high level overview. Whenever any JSF page is requested, we will check the cache, and if not available, we will delegate to JSF while also saving to cache. If it is in cache, we will merely use that file rather than going through the JSF lifecycle. HTTP servers are very fast/efficient at serving static resources, so you should easily see millisecond access times.

Read the rest of this entry »

JSF Relative Client IDs

October 13th, 2008

Currently in JSF, if you wish to have one component refer to another component, you have to use one of two types of client ids: absolute or relative. A relative id is resolved against its closest parent NamingContainer and searches for a suitable match. An absolute id starts with a separator character (typically a colon) and references the top most view root object of the tree. These solutions both work great and generally you rarely need to use absolute ids, which I always feel should be strayed away from as it adds to maintenance and bug leaks. For example, if you change a parent client id, you may forget to update absolute ids that had depended on that particular id. The result is a broken page that may slip through testing leading to bugs. Thus, I always prefer relative URIs when possible. However, in JSF there is no good way in 1.x to refer to parent element relatively. For example, if you have a component within an iterative component (data table, repeat, etc) and wish to refer to a component outside the iterative section, you must currently use an absolute id. Using a relative id would result in a failed lookup as the relative URI only resolves against the closest naming container, which would be the iterative section. However, using an absolute URI (which does work) results in harder to maintain code. A more ideal solution, IMO, is to use relative paths such as Linux (or most other operating system shells) to refer to the outer parents. For example, given the previous iterative example, you could use an expression such as for=”..:child:id” where “..” goes to the parent naming container of the closest naming container. Now, you have relative URIs and much easier to maintain code by not having to worry about potential id changes to the root element, for example.

Controlling GC and Improving Unit Testing through Factories

October 13th, 2008

So I was looking at design patterns and read across the factory pattern and the pooling pattern. I know what both of those do independently but never considered them together and as a result, my mind started racing with ideas. One of the many problems with applications in terms of performance is garbage collection. Pooling helps to solve this problem by reusing objects that have been released back to the pool. One of the big problems with unit testing is testing classes in pure isolation by properly injecting mock objects that are dependencies of the class under test. IoC helps to resolve this issue by injecting code into classes. However, you still have to at times use ‘new’ to create objects. This causes three big issues. First, the VM has to create a new object, initialize it, and add it to the stack. This is an expensive task. Second, you put dependency into the code. Further, if you utilize pooling you add yet another dependency (think coupling here). Third, using new does not allow you to truly run code in isolation as your class under test is not invoking code on another object without being able to use a mock instance.

So, how can you solve these problems, you ask, and what do they have to do with factory and pooling design patterns? Well, let’s go back to my initial remark on the factory and pooling design patterns. First, we will talk about the factory design pattern. A factory design pattern is simply a class that loads or creates other classes. That is exactly what we want to do. Further, this allows us to do a few things. First, it abstracts how an object is created and lets you add custom handling to any type of object by simply using a different factory. This helps to reduce other less performance-based solutions such as AOP or adapters and wrappers. Second, it removes the usage of the new operator so that you can easily mock the class under test in pure isolation by registering mock objects with the factory. Third, it promotes loose coupling by not having classes worry about pooling, initialization, etc. POJOs only depend on the Factory as a simple static object. With that said, let’s look at some examples to further clarify.

Read the rest of this entry »

HTML5 Adoption via Emulation

October 11th, 2008

The biggest issue right now with web related specifications is browser adoption. The specs clearly state that at least two mainstream browsers must implement the standard to be considered complete. In most cases that tends to be Firefox, Opera, Safari, and Internet Explorer. The first of these three has always been adapt to adopting standards. The latter is only just beginning to catch up. This results in most of the web authors in the community from not utilizing new features as it results in having to maintain different sites for different browser capabilities. So, how do we change this?

First, as web authors, we need to start showing the promise of future specs like HTML5 in order for browser vendors to realize the promise and create a higher urgency to update their applications. But how can we implement new HTML 5 features without browser support? The answer to that is through emulation. If you look at many of the libraries already on the web, much of this is already in the works, even if not explicitly stated. For example, Google Gears allows authors to utilize the new HTML5 storage support. Javascript libraries such as jQuery support future CSS 3 selectors. The dojo javascript library provides many of the networking stacks and future AJAX support. The piece that is missing is a full emulation layer the builds on those already available but allow a document to be built on HTML5 and rendering the result on the client side.

Imagine the advancement for authors if an emulation layer existed. For example, rather than having to use the APIs within existing libraries to create a calendar control, you could simply drop a date input onto the page via HTML5’s <input type=”date” />. The emulator would pick up that tag and properly utilize the libraries to build the control. This simplifies author development, starts to show the promise of HTML 5, and helps the end user by providing the new features of HTML5. Similar to how browsers adapt pieces of the spec at a time, this emulation layer could provide the same result. However, rather than having to rely on browser developers to find time to build the feature, the emulation layer can use the open source community and the already existent libraries to more quickly adapt features. The features would be smart in that they would fall back to the native browser support, if provided. It would only emulate when non-compliant browsers are used. The end result of all of this is that we build HTML5 pages today and can easily drop the emulation libraries once full support is provided.

I plan to eventually create an open source project and host it to the open source community in order to drive this into existence.  Over the next month I will be analyzing the HTML 5 spec and the already existent libraries to determine some various paths to proceed under.  If anyone is interested in joining, shoot me an email or a comment.  You can follow all of my progress on this blog.