Thursday, August 30, 2012

Incremental build with RichFaces CDK


To whom of us using RichFaces CDK and being unsatisfied with a build time, our day just came!

CDK got an incremental build feature, which caches information collected during a Library compilation and store it on a hard drive.

Once you trigger a build for a second time, the last modification time of all sources is compared to last modification time of cache file.

When CDK recognizes that any source has changed, it will re-compile it and the collected data will be applied on Library model again, effectively rewriting old data.

How to Configure Incremental Build

How to configure incremental build in your CDK project? It's pretty simple: you don't need to do anything.

Incremental build is turned on by default to make your life easier and to save your precious time.


I recommend you to configure the fast CDK turnaround using JRebel - together with the incremental build, nothing will beat you in the rich JSF components development time.

Troubleshooting

When using incremental build at current implementation, be aware that in some cases when you do structural changes (e.g. renaming methods), you may get to a point where the incrementally generated sources will not be valid - sometimes it won't make any trouble (attribute renaming), sometimes sources generated by CDK might not be even compilable at all.

In this case, you just need to recompile the sources from scratch, either with additional maven-cdk-plugin configuration

$ mvn cdk:generate -Dcdk.recompile=true


or using command line interface:

$ bash run.sh --force-recompile

However in most cases, incremental build will work just fine. :-)

Improvement

Using incremental build, I have achieved build-time improvement from 10 545 ms to 1 622 ms in Bootstrap sandbox project.

Such an improvement will allow us to re-factor RichFaces component suite to be developed just from one maven module and simplify a build a lot.

Enjoy JSF component development

Friday, August 3, 2012

JSF meets Skinning Awesomeness of LESS

A strength of JSF is in how it enables you to quickly write applications, providing you with a plethora of components abstracting complex functions.

Skinning, Styling & CSS



But when it comes to skinning and styling those components, JSF is not very helpful. But let’s not malign JSF here - it's not the fault of JSF.

Rather, we should blame CSS, which lacks the dynamicity that would allow the strong skinning features.


CSS Pre-Processors to the Rescue


That's exactly where technologies like LESS and SASS come in. They are processors which provide an  alternative syntax similar to CSS, that basically allow you to do magic with your style-sheets and how they are are structured - variables, mixins, functions, etc.

As the RichFaces team is currently working on leveraging Twitter Bootstrap, we want to embrace its beauties completely, and thus adopted its ability to style components in a simple and reusable way, while also enabling style extensions.

Now, you can see this magic in the RichFaces Bootstrap showcase.

What is this magic and how you can achieve it? Let's see in this demo:



Incredibly fast styling with JSF and LESS from Lukas Fryc on Vimeo.


You can clone the Bootstrap showcase on GitHub repository:

https://github.com/richfaces/sandbox

How does it work?

When the project is imported to the IDE, you can achieve instant turnaround without need to reload (or even re-deploy) anything - you just turn on the Instant LESS functionality using a bookmark with the following URL and the client-side LESS compiler will take care of the rest:

javascript:less.instant.toggle();


Your browser will now constantly watch for changes in the application resources.

We use JRebel to ensure resources are pushed to the server immediately after we save them in the IDE. This isn't necessary if you use an expanded WAR, but we load LESS resources from JAR projects and that's where servers usually fall short. Luckily JRebel comes to save our butt, making possible the hot-reloading of resources within a JAR that are served using the JSF Resource Handler.

Production Mode

The above method works well while in the Development stage of a project. But with that approach, LESS compiles resources in the browser and thus would slow down your application.

In Production project stage is where built-time compilation comes into play. We use the popular project wro4j - a pre-processor, minifier and optimizer for many alternative syntaxes for web languages.  Specifically we are using the wro4j-maven-plugin and M2E connector for this Maven plugin (written by our fellow Fred Bricon, who wrote a blog about usage of this plugin).

Let's check the Production Mode out, it is also as awesome as the Development Mode and its instant turnaround feature!

Monday, May 14, 2012

In the foothills of Alps - wrap-up of ConFess 2012


Last week, I have been in Austria at ConFess conference.

From my perspective, the conference underwent two significant changes: the venue was moved to Leogang, Austria and at second I was speaking there. :-)

For the first point, I really loved the place - I'm the big fan of hiking and alpinism, so I really enjoyed the moments when we were discussing outside the conference rooms, breathing the fresh air and admiring the beauties of surrounding nature.



At second it was really pleasure to speak at ConFess, as it is the first conference where I've ever been, and I like returning there.



My first talk was about latest movements in world of HTML5, what developers needs to consider and how JSF and RichFaces fit that story.



Second talk was structured as comprehensive guide to designing test suites for Java EE applications. I have revealed some of latest movements at planet Arquillian (like JSFUnit.NG or JRebel extension).

Thanks to Jan Papousek who captured the photo.

Wednesday, April 11, 2012

Graphene 1.0.0.Final Released

The Arquillian Graphene, the project focusing on making a real-browser automation a breeze, is now reaching first Final release.

The Graphene is joining rest of the Arquillian party, building on top of Arquillian framework integration and Drone extension, which reached their stable version yesterday.

The Mission

The project was started to address simplification of covering AJAX-enabled applications with browser automation tests.

While Selenium project is focusing on unified API, integration with variety of browsers, Graphene project is addressing the real-world testing challenges:
  • rapid development
    • straight-forward
    • readable API
    • fast turnaround
  • object-oriented
    • type-safe API
    • dependency injection of thread-local context
  • instabilities and speed of execution in continuous integration
    • jQuery selectors
    • request guards

Availability

The Graphene bits are available in JBoss Maven repository, dual-licensed under LGPL v2.1 (backward-compatibility) and ASL v2.0 (which uses rest of the Arquillian sub-projects).

For those who are already using the framework with Maven, you can simply increase the version to 1.0.0.Final.

You can start with the tests using our Getting StartJBoss Maven repositoryed guide.

The Future

Right now we are heavily working on making the new version of Graphene 2 on the road.

Selenium 2 with its WebDriver API made huge progress with API accessibility and readability - it's already pleasure to work with this API in Java world.

However still there are many lacks we are going to address with Graphene 2, building on top of concepts brought in Graphene 1 and adding new features, which opens world of new possibilities:
  • dependency injection of thread-local context
  • fast development turnaround
  • cross-cutting concerns (command interception)
  • request guards
  • page extensions
  • component objects
    • extension of page objects concept
  • JavaScript test execution from within Selenium test
If you enjoy testing and you are unsatisfied with the current browser automation tooling, it's perfect time to step in and help us to bring the future!

The Project Info

Wednesday, April 4, 2012

Full-Fledged Debugging for Mobile Browsers

A debugging of desktop applications is very common task in the world of web development. We might say the tooling here is highly developed and you can find everything you require and pretty easily. You can just use all those Firebugs, Chrome Web Inspectors, IE Developers Tools, etc.

Not so in world of mobile devices!

Hard Time Debugging Web Apps on Mobiles

The debugging applications on mobile were always problem - the mobile safari for iPhone/iPad offers you at least error console, so you might know when something is going wrong. The Android built-in browser does not even provide you such tool!

WebKit Web Inspector

But the WebKit based browsers has solution to this - they offers WebKit Web Inspector, which you might be familiar with from using Chrome/Safari.

Fortunately, WebKit functionality has arrived to mobile browsers yet!

Inspector for Safari / iPhone

From little bit of search, I have found Safari was enabled to use remote debugging bridge year ago!

Inspector for Chrome Beta / Android

But as Ubuntu/Android user, I wasn't able to use such a comfort. Until now!

I have upgraded my HTC to Android 4 yesterday and the Chrome Beta was the first application I installed there (it isn't available for previous Android releases).

Today I have dived into RichFaces issue which occurred on mobiles. What a pain it could be when trying to find the cause, since mobile browsers doesn't even provide you the exact line where JavaScript error has occurred.

And guess what? Chrome Beta already allows the same like Safari - WebKit Web Inspector through the USB debugging bridge.

How To...

The process is quite straight-forward:

Thursday, March 29, 2012

Incredibly Fast JSF Component Development

Why is a JSF components development so painful?

It would be really great if I could develop full-blown JSF components wrapping some JavaScript UI widget as fast as I'm developing plain HTML, wouldn't it?

Just two words: fast turnaround!

Every tool and every framework which tries to simplify a process should have a strategy to allow a fast turnaround. It is lowering a learning curve and saves developers many invaluable hours. And mainly it makes working with the a tool a pleasure!



RichFaces CDK


The CDK project is sample of such a powerful tool - it allows you to write just two pieces -
  • a Java component interface,
  • a HTML renderer (with Facelets-like syntax),
and then it takes these definitions and
  • generates all the boilerplate code automatically including
    • all the Java code,
    • configurations (faces-config.xml and *.taglib.xml),
    • and a VDL documentation.
Brian Leathem has written series of articles introducing how easy can JSF component development be when using RichFaces CDK.

But besides it is the powerful tool, you can also achieve a really fast development turnaround using CDK- just by using proper tools!


Quick Turnaround with RichFaces CDK


There is guide which covers how to setup your tooling to start with a development.

It covers setting up the component and demo project in JBoss Tools (on top of Eclipse IDE) and how to automatically trigger build when you change CDK resources.

And to make the deployment phase as quick as possible?

We are using JRebel to hot-deploy built resources into JBoss AS 7, which is itself f&@#ng fast.

That's it!

You can just save & refresh the page!

The pictures used in the blog are only illustrative, taken by various authors and published under Creative Commons license. The references: the toolkit by Ryan Hyde and the trains by Joel Down

Monday, March 19, 2012

Graphene CR3 Released & How To Migrate from Ajocado?


The project Ajocado has been renamed to Graphene.

The first release under the new name waits for you in Maven repositories.

Migration Path

Fortunately, the migration to new name in your project is very smooth, you can even continue to use original APIs.

Java Classes

The packages of the Java classes have not been renamed, the only change is addition of three new interfaces/utilities and deprecation of the old ones:

Ajocado -> Graphene
AjaxSelenium -> GrapheneSelenium
AjocadoConfiguration -> GrapheneConfiguration
AjocadoContext -> GrapheneSeleniumContextM
AjocadoConfigurationContext -> GrapheneConfigurationContext

The original names has been deprecated, but it doesn't prevent to use current tests as they are - the deprecated classes will continue to be part of the project.

Configuration

The simple change in the arquillian.xml descriptor is needed, you just need to change ajocado to graphene:

<extension qualifier="graphene">
    ...
</extension>

Maven Artifacts

The most significant change underwent dependency system, so let me talk a more little bit about that:

In Ajocado CR2, there was only one dependency necessary to import all the JUnit/TestNG and all Arquillian dependencies.

In Graphene CR3, you need to manage several dependencies - however it makes your usage of dependencies little more cleaner, since you know exactly what dependencies are imported.

At first, you need to import JUnit/TestNG dependency:

Test Framework

<!-- JUnit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.8.2</version>
    <scope>test</scope>
</dependency>

<!-- TestNG -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>5.14.6</version>
    <scope>test</scope>
</dependency>


Additionally, you need to choose between using Graphene as standalone or use Arquillian integration with containers:

Standalone Usage

In this mode, you don't use integration with containers, you need to manage the container and deployment at own:

<!-- Arquillian JUnit Standalone -->
<dependency>
    <groupId>org.jboss.arquillian.junit</groupId>
    <artifactId>arquillian-junit-standalone</artifactId>
    <version>1.0.0.CR7</version>
    <scope>test</scope>
</dependency>

or

<!-- Arquillian TestNG Standalone -->
<dependency>
    <groupId>org.jboss.arquillian.testng</groupId>
    <artifactId>arquillian-testng-standalone</artifactId>
    <version>1.0.0.CR7</version>
    <scope>test</scope>
</dependency>


Container usage

In the container mode, you need to provide deployable archive  (@Deployment) and the whole lifecycle of the container and deployment will be managed by Arquillian:

<!-- Arquillian JUnit Container -->
<dependency>
    <groupId>org.jboss.arquillian.junit</groupId>
    <artifactId>arquillian-junit-container</artifactId>
    <version>1.0.0.CR7</version>
    <scope>test</scope>
</dependency>

or

<!-- Arquillian TestNG Container -->
<dependency>
    <groupId>org.jboss.arquillian.testng</groupId>
    <artifactId>arquillian-testng-container</artifactId>
    <version>1.0.0.CR7</version>
    <scope>test</scope>
</dependency>

Graphene Dependency Chain

And finally it's necessary to import Arquillian Graphene dependency chain, which includes all other necessary dependencies (Graphene, Drone, Selenium):

<!-- Graphene dependency chain -->
<dependency>
    <groupId>org.jboss.arquillian.graphene</groupId>
    <artifactId>arquillian-graphene</artifactId>
    <version>1.0.0.CR3</version>
    <type>pom</type>
    <scope>test</scope>
</dependency>

What's next?

We are preparing to release Final later soon, the same as other dependencies in Arquillian ecosystem.

Thanks all the people who helped to test migration (Jan Papousek, Karel Piwko), so it is now pretty smooth.


More project information

Home page
Documentation
Issue tracker

Goodbye, Ajocado - Welcome, Graphene!

Goodbye, Ajocado

Wait, the Ajocado project is not leaving us!
It is just undergoing rename. Why such a change?

Ajocado was everytime proud member of Arquillian family, however its name didn't tell very well what's its purpose in the true alien world - the name didn't fit the story.

Moreover, we have experienced many troubles explaining how Ajocado should be even pronounced.

I must admit it was unlucky choice.

Choosing the new name...

The project is like a diamond - very strong in its basis:
  • a strongly-typed, chaining API
  • efficient jQuery-based locators
  • proven to handle AJAX successfully
But on the other hand, diamonds can't be simply manufactured.

Let's look what more could Ajocado offer us:
  • rapid test development
  • readability
  • high-level abstractions
What can be as strong as diamond, but be much more flexible?

Welcome, Graphene!

Graphene is stronger and stiffer than diamond, yet can be stretched by a quarter of its length, like rubber.
Let me introduce the Graphene - the strong and flexible UI automation tool - the old/new member of the alien crew, on the way to save the world!

What's next?

The rename is already done, waiting in maven repositories as Graphene 1.0.0.CR3.

And what about migration? It's pretty straight-forward, as you can see in my next post.

Thank you all who participated in choosing new name, renaming and migration testing (Vlasta Elias, Dan Allen, Jan Papousek, Karel Piwko)!



More project information

Home page
Documentation
Issue tracker

Tuesday, March 13, 2012

Great times at JDC 2012, Egypt


I’m finally back from Cairo, where I was invited as speaker on Java Developer Conference 2012.

If I should think of just one word explaining the conference, I would need to say: a passion.

You could seen the passion from everywhere: discussions, an audience, follow-up questions, organizers.

As I have written in last post, I had three sessions there - you can read more about them or view the slides at Lanyard:





The only what would I change is timing of sessions, because then me and Koen’s session had not conflict and Arquillian would take even more attention.


I have spent lot of time in the JBoss booth and the venue, discussing precious projects!



After the conference closing, the good beer and the nice mood over the discussion about various, mainly JBoss-related and philosophical questions with Koen made my Sunday's waking up really hectic - I arranged the trip over the pyramids for 9:00. Although the clock in the room was showing 6:25, it was nearly 9:30.

But the morning’s difficulties were quickly shaded with all the great views on pyramids - there were so nice and as Koen expressed it exactly: mind-blowing. I really need to give another thanks to the our tour guide - Mahmud for taking us all - me, Jonaas and Richard - to the pyramids.


At overall, I would be really happy to speak at JDC again next year as well as discover other beauties of Egypt!


Monday, March 5, 2012

Speaking at JDC'12 in Cairo, Egypt


I'm speaking at JAVA Developer Conference 2012 held at March 9-10th in Cairo, Egypt.

I will give there 3 talks on my favorite topics: a web development with JBoss technologies and a testing.

The Gear You Need To Go Mobile With Java Enterprise
In the first talk, I'm going to cover what could the Java enterprise offer you in days of a rising mobile platform.

A Rapid JSF Component Development with RichFaces CDK
The second talk introduces RichFaces Component Development Kit as the tool to cover the space where JSF2 falls short - custom component development.

Arquillian: Effective Tests from the Client to the Server
The last talk is about the latest movements in the space of a testing revolution started when Arquillian decided to save the earth. I will focus specifically on testing an integration of the client and the server.


My JBoss fellow, Koen Aers, will be also presenting there and he covers lot of interesting stuff: JBoss Tools, Forge and Arquillian (yeah, Ike invades Egypt!). Let's checkout his and other sessions.

The event haven't started yet, but it's already looking like great event, I'm looking forward to see you there!

Friday, February 24, 2012

Wrap-up: Arquillian Hackfest @ Developer Conference 2012 Brno


Thank all participants for contributing to discussions on Arquillian HackFest!

The 10 people has attended and shared their ideas on selected topics,
and others came to see us on video stream and IRC channel!


The initial idea for this Hackfest has arisen when we were discussing the topics we would like to cover in conference days, just after Arquillian SPI talk from Aslak.


Although we wasn't able to cover all declared topics,
we focused on the ones which were most related to incoming Arquillians,
the notes and white-boards can be find here:

Future: GWT

Future: JavaScript

Future: Performance testing

Future: JSFUnit.NG
( no notes here, it was really short session - after Arquillian SPI talks, it didn't left much more to discuss - thanks Aslak! )


It was pleasure to see so much ideas flowing, let's grab them and equip Ike with even more mighty weapons for fighting with bugs. ;-)

Monday, February 13, 2012

Re-routing JSF resource requests with RichFaces Resource Mapping

Note: The implementation contains issue, thus the samples from this blog needs to be slightly modified, details in this comment. The fix will be available with RichFaces 4.2.1.CR1.

RichFaces resource mapping can save your life when you need to serve a different resource (JS, CSS, image) file than the one originally requested. It works in the stage of determination of the resource request path.

Specifically in all following situations, it may be really handy:
  • providing alternative versions of a resource
  • map several resources to one
  • using external resources
  • moving resources to servers with static content
Before diving deeper into the situations above, let's look at how resources typically works in JSF.

Resource loading in the picture

Component libraries bundle resource dependencies (CSS stylesheets, JavaScript sources, images) in the distribution archives (JARs) and application-specific resources are bundled in WAR - the situation is outlined on the following picture:

Component libraries (JARs) and application web archive (WAR)
and resource dependencies (green)


Let's look at all of mentioned situations one by one:

Providing alternative file

For example, your application requests jquery.js resource, but you don’t want to use default one, you want to provide alternative, maybe patched version to solve some issues. So you provide RichFaces the mapping using following configuration.

Create the file META-INF/richfaces/static-resource-mappings.properties on the classpath of your project and configure one mapping:

jquery.js=jquery-alternative-version.js


All requests for jquery.js will then be served as requests for jquery-alternative-version.js.

jquery.js mapped to jquery-alternate.js

Warning: Resource mapping requires resource servlet for its work - it is automatically registered in Servlets 3.0 environments (JBoss AS 6 and 7, Tomcat 7, GlassFish 3, etc.), but you will need to register that manually in Servlets 2.5 or lower environments - see RichFaces Developer Guide for details of how configure it.

Note: This mapping file needs to be placed in one of following locations: 

{MAVEN_WAR_PROJECT}/src/main/resources/META-INF/richfaces/

{JAR}/META-INF/richfaces/ 

{WAR}/WEB-INF/classes/META-INF/richfaces/

Note: jquery-alternative-version.js needs to be placed in your project on one of following  locations (JSF resource: 

{MAVEN_WAR_PROJECT}/src/main/webapp/resources /

{MAVEN_JAR_PROJECT}/src/main/resources/

{JAR}/META-INF/resources/

{WAR}/resources/
Another example

Or you can similarly map jsf.js resource:

javax.faces\:jsf.js=patched-jsf.js
Note: notice the backslash before the : (it is the escape sequence, required in the properties file)

Map several resources to one

Another requirement comes when you are using several component libraries in one project - oh crap, and they all are based on jQuery and each of them uses another version!

One of solutions here (except using jQuery.noConflict()) is map all requests for different jquery.js versions to one. Let’s define following mapping:

# RichFaces bundled jQuery (following line is not necessary)
jquery.js=jquery.js

# PrimeFaces bundled jQuery
primefaces\:jquery/jquery.js=jquery.js

# Another project bundled jQuery
another\:jquery.js=jquery.js


Okay, now all these libraries use only one version of jQuery - the RichFaces one. ;-)

another:jquery.js mapped to  jquery.js


Using external resources

But resource mapping isn't used only for mapping requests to serve local resources, but external HTTP resources can be served as well.

Let’s show-case this on sample of mapping requests of jQuery library to CDN [1].

jquery.js=http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js

jquery.js mapped to CDN resource


Moving resources to servers with static content

With RichFaces, you can even move all your resources to a server which serves static requests (like Apache Httpd) to lighten your application server. Just map all your resources to HTTP locations.

All application resources are mapped to static server.



That's it, RichFaces Resource Mapping really can save your life! ;-)

Thursday, February 9, 2012

Optimizing Resource Loading with RichFaces 4.2

HTTP connection is an expensive commodity. But if you will look on a traditional rich JSF application, there are many resources for components which need to be loaded, thus many connections need to be established.

The high number of HTTP requests significantly affects application load time and thus overall performance. This applies especially for high-latency network connections like geographically distant places and for mobile networks.

Here you can see profile of loading RichFaces page. You can view sequence of requests made by browser to load all the page dependencies.

JavaScript dependencies

CSS dependencies

When you will look into page source, you will see these resource dependencies defined in the head of the page:

<head> section will all the dependency links


Simple optimization of resource loading comes in form of aggregating several requests into one, thus lightening the load on both the server and the network.

The RichFaces Way

RichFaces offers you the simplest solution available - all RichFaces resources packaged in one file for each resource type - one JavaScript package (packed.js), one CSS package (packed.css).

The only thing you need to do is turn the packaging feature on.

Enabling resource optimization

Open the web.xml file in your project and add following lines:

<context-param>
    <param-name>org.richfaces.resourceOptimization.enabled</param-name>
    <param-value>true</param-value>
</context-param>
Notes: Resource optimization was introduced in RichFaces 3.x as resource loading strategies.

It was reintroduced in 4.1, but for 4.2, its configuration was slightly changed to be more clear and concise. This blog reflects changes committed with RichFaces 4.2.0.CR1. Read more about changes in release blog.

Now, deploy and open your application. When you will open page source, you can see that number of page resources (<script> and <link> elements in the head) was significantly decreased:

<head> section with links to optimized resource dependencies


Also the page load profiles looks much better:

Optimized JavaScript resources

Optimized CSS resources


Packaging and Compression

Resource optimization itself is composed from two features: packaging and compression.

Packaging phase aggregates several resources into one, while compression do JavaScript/CSS compression and obfuscation (powered by YUI compressor).

By default, both packaging and compression are applied on RichFaces resources (in production stage).

However resource optimization is also controlled by the stage of the project. Why?

Development mode

Packaging is not convenient in development project stage.

When you are developing application, some problems may occur in form of JavaScript errors or wrong look because of styling issues. In these cases it’s handy to debug these JavaScript or CSS resources in uncompressed state.

The state of the project is controlled with web.xml switch:

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

It will force load uncompressed, but packaged resources - great for debugging the app!

Troubleshooting

When you will have any issues, be sure to look into

Troubleshooting - Resource Optimization article


Summary

As you can see, with RichFaces Resource Optimization, you can achieve decrease of number of resource requests. These resources are also cached by the browsers, so after first page, client get perfect responsiveness.

On the other hand, you are increasing the size of resources which are necessary to be loaded on first request, since all of the RichFaces component resources are bundled in one file.

You need to choose between fast start of the app and responsiveness of the app after first request.

What's the best option for your application, it’s up to you! ;-)

Future Improvements?

We have several ideas how to improve resource loading if it is really critical for your application:

  • several smaller files packaged for certain occasions (core, tables, panels, etc.)
  • provide you maven plugin which will create custom packages just to fit your application needs during the application build!


If you would like to implement any of these features, or have any other ideas for enhancements, be sure to let us know!

Wednesday, February 8, 2012

4 simple steps for RichFaces Push with 4.2


RichFaces Push is a pretty useful component, since it enables you do a server-side push technique (pushing content from a server to a client asynchronously). What makes this component so attractive when there are plenty of other ways to achieve this?

RichFaces is enabling application developers to build on top of push without any additional complexity.

It is enough to use only one interface (which can even be injected using CDI) on the server side. And you need only one component on the client side: <a4j:push>.

In this blog, I’m not going to show all possibilities of how to use the RichFaces Push - instead, I will show you, how to configure this component to work on your favorite container including small sample page and bean. Why?

We have simplified Push drastically along the way from 4.0 to 4.1 and we are continuing in 4.2 to make the process of setting up a project with Push as simple as possible! That’s why I’m sharing our progress with you.

Let’s start...

We will start with SimpleApp maven archetype - it doesn’t have Push configured. It assumes that you have following dependencies installed:
  • Maven 3.0.3+
  • JDK 1.6
  • your favorite editor
  • your favorite servlet container or application server

Creating the project stub

Okay, let’s create the new app based on the SimpleApp archetype:

mvn archetype:generate -DarchetypeGroupId=org.richfaces.archetypes -DarchetypeArtifactId=richfaces-archetype-simpleapp -DgroupId=my.domain -DartifactId=simplepush -Dversion=1.0-SNAPSHOT -Dpackage=my.domain -DarchetypeVersion=4.2.0.CR1


Note: RichFaces Developer Guide may help you when you get stuck with setting up environment:


We have created a stub for our application, now you can try to deploy it on your favorite container and verify basic functionality:

http://localhost:8080/simplepush/

You should see one ajaxified input and when typing, you should see appropriately updated output.

4 simple steps for Push

What are the modifications we will undertake next?
  • install Atmosphere libraries
  • register a servlet (if necessary)
  • add a managed bean with an action triggering a push event
  • add an a4j:push component to the a page

Installing Atmosphere libraries

Atmosphere is the only runtime dependency for RichFaces Push. Atmosphere enables integration with various containers and interoperability between browsers and push techniques (websockets, long-polling).

In order to install Atmosphere in your project, add following lines into your pom.xml, in the section <dependencies>:

<dependency>
    <groupId>org.atmosphere</groupId>
    <artifactId>atmosphere-runtime</artifactId>
</dependency>

Note: version of the dependency is automatically managed by importing the richfaces-bom, that’s why you don’t need to specify <dependency><version> here.

Registering PushServlet

RichFaces Push requires PushServlet registered for web application in order to connect to a container and listen for push requests.

In Servlets 3.0 and higher environments (JBoss AS 6 and 7, Tomcat 7, GlassFish 3, etc.), the servlet will be registered automatically by including RichFaces Core libraries on classpath.

However in Servlets 2.5 and lower, servlet needs to be registered manually in web.xml:

<!-- Push Servlet - listens for user sessions -->
<servlet>
    <servlet-name>Push Servlet</servlet-name>
    <servlet-class>org.richfaces.webapp.PushServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Push Servlet</servlet-name>
    <url-pattern>/__richfaces_push</url-pattern>
</servlet-mapping>

<!-- setups servlet-mapping in RichFaces configuration -->
<context-param>
    <param-name>org.richfaces.push.handlerMapping</param-name>
    <param-value>/__richfaces_push</param-value>
</context-param>

Adding action to the managed bean

Let’s open and edit RichBean.java under src/main/java in package you have defined. Add following methods:

public Date getDate() {
    return new Date();
}

public void push() throws MessageException {
    TopicKey topicKey = new TopicKey("sampleAddress");
    TopicsContext topicsContext = TopicsContext.lookup();
 
    topicsContext.publish(topicKey, "empty message");
 
    System.out.println("push event");
}

Adding component to the page

Open and edit index.xhtml file under src/main/webapp directory.

Replace contents inside of <h:form> with following snippet:

<a4j:commandButton value="Push!" action="#{richBean.push}" />

<a4j:push address="sampleAddress">
    <a4j:ajax event="dataavailable" render="outputDate" />
</a4j:push>

<a4j:outputPanel id="outputDate">
    Date: #{richBean.date}
</a4j:outputPanel>

Accessing sample

When opening http://localhost:8080/simplepush/ again, you should see one button and output with the date.

When clicking on the button, the date should be updated.
But it’s not simple AJAX!

In the background, <a4j:push> opens long-lived session to the server. When you hit button, a server action method publishes the message and RichFaces sends it to all clients which are subscribed to listen on given address topic (determined by the TopicKey). When clients receive that message, an event is fired in order to trigger an AJAX update of the date output.

An advantage over the traditional poll technique is that clients are updated without the necessity of periodically connecting to the server - it off-loads server and provides immediate client updates.

Note: I know, this sample is quite artificial, because real-world applications won’t use a4j:push and updated area on the same page, but the purpose of the blog was mainly show you configuration of the RichFaces Push.

Troubleshooting

If anything didn’t work for you, perhaps you just used the wrong environment and/or you need to configure something additionally, just look at Starting with RichFaces Push on Various Containers article.


Summary

It was necessary to only add Atmosphere libraries to the project generated from SimpleApp archetype, we have made sure that the push servlet is registered and we have setup page and bean with action simply - just enough for showcasing Push component.

Pretty simple, isn’t it?

Who knows what I will cover next time regarding the Push technology in RichFaces? :-)

Hmm, just stay tuned!