Easy Ajax Push

Table of Contents

Easy Ajax Push Tutorial

Ajax Push is a common Web 2.0 term that describes a technique of sending (or "pushing") data from the server to the client in an asynchronous manner. Ajax Push in ICEfaces 3 allows the application to incrementally update any part of the page at any time, for any group of clients, enabling collaborative multi-user applications where the actions of one user can be instantaneously communicated to other users. Ajax Push in ICEfaces 3 is based on an underlying asynchronous notification mechanism called ICEpush.

You should review the Ajax Push Overview and API before proceeding.

The goal of this tutorial is to create a basic ICEfaces 3 project and add collaborative interactions with Ajax Push. The example will allow multiple client sessions to choose colors and have their selection displayed to everyone looking at the application.



Development Tools Used

The following tools were used to create the project.

1. Make the easyAjaxPush Project

  • Using Eclipse create a new Dynamic Web Project called easyAjaxPush.
    • Target runtime: Apache Tomcat v7.0
    • Dynamic web module version: 3.0
    • Configuration: JavaServer Faces v2.0 Project (Mojarra)

2. Add ICEfaces and ICEpush

Add the icefaces.jar and icepush.jar (from the ICEfaces 3 bundle) to your project, either through a custom User Library or by putting them into easyAjaxPush/WEB-INF/lib/. The approach doesn't matter as long as the jars are included in the deployed war file.

3. Create color.xhtml

Create a new page called color.xhtml and paste the code below:

color.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
<h:head>
	<title>Easy Ajax Push - Color</title>
</h:head>
<h:body>
	<h:dataTable value="#{messageBean.textList}" var="current">
		<h:column>
			<h:outputText value="#{current.text}"
						  style="color: #{current.color};"/>
		</h:column>
	</h:dataTable>

	<hr width="100%"/>

	<h:form>
               <h:panelGrid columns="2">
			<h:outputText value="Your session id:" />
			<h:outputText value="#{colorBean.sessionId}" />
		</h:panelGrid>
		<hr />
                <h:panelGrid columns="4">
			Choose a Color:
			<h:commandButton value="Red"
                                         action="#{colorBean.chooseColor}"
                                         style="color: white; background-color: red;">
				<f:setPropertyActionListener target="#{colorBean.color}" value="red"/>
			</h:commandButton>
			<h:commandButton value="Blue"
                                         action="#{colorBean.chooseColor}"
                                         style="color: white; background-color: blue;">
				<f:setPropertyActionListener target="#{colorBean.color}" value="blue"/>
			</h:commandButton>
			<h:commandButton value="Green"
                                         action="#{colorBean.chooseColor}"
                                         style="color: white; background-color: green;">
				<f:setPropertyActionListener target="#{colorBean.color}" value="green"/>
			</h:commandButton>
		</h:panelGrid>
	</h:form>
</h:body>
</html>

The purpose of this page is very simple and will display a list of messages and a few buttons to choose a color. When you choose a color an associated message will be added and Ajax Push will send this change to any other client sessions viewing the page (because of how the push group will be setup).

4. Create MessageBean.java

Create a new Java class file called MessageBean in the package org.icefaces.tutorial.easyajaxpush.beans and paste the code below:

MessageBean.java
package org.icefaces.tutorial.easyajaxpush.beans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

import org.icefaces.tutorial.easyajaxpush.model.TextModel;

@ManagedBean(name="messageBean")
@ApplicationScoped
public class MessageBean implements Serializable {
	private static final int MAX_SIZE = 25;

	private List<TextModel> textList = new ArrayList<TextModel>(0);

	public MessageBean() {
	}

	public List<TextModel> getTextList() {
		return textList;
	}

	public void setTextList(List<TextModel> textList) {
		this.textList = textList;
	}

	public void addToList(String sessionId, String color) {
		textList.add(makeTextModel(sessionId, color));

		if (textList.size() > MAX_SIZE) {
			textList.clear();
		}
	}

	private TextModel makeTextModel(String sessionId, String color) {
		return new TextModel("User with session ID of " + sessionId + " selected color \"" + color + "\".",
						     color);
	}
}

This class is ApplicationScoped (using annotations) and will store a list of TextModel objects. As you've seen above, the list will be displayed in the view (color.xhtml) using an h:dataTable.

The actual text of each message is generated in this class based on the HTTP session ID and the selected color. The resulting message looks similar to:

Example Message
User with session ID of 8B562014110E53F984745DB12F68A57B selected color "red".

Note that this class will stop the list from growing beyond MAX_SIZE (default 25), but otherwise is fairly basic.

5. Create ColorBean.java

Create a new Java class file called ColorBean in the package org.icefaces.tutorial.easyajaxpush.beans and paste the code below:

ColorBean.java
package org.icefaces.tutorial.easyajaxpush.beans;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

@ManagedBean(name="colorBean")
@ViewScoped
public class ColorBean implements Serializable {
	private static final String PUSH_GROUP = "colorPage";

	@ManagedProperty(value="#{messageBean}")
	private MessageBean messageBean;
	private String color = "black";
	private String sessionId;

	public ColorBean() {
		FacesContext fcontext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession)fcontext.getExternalContext().getSession(false);
		sessionId = session.getId();
	}

	public void setMessageBean(MessageBean messageBean) {
		this.messageBean = messageBean;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String chooseColor() {
		messageBean.addToList(sessionId, color);

		return null;
	}

        public String getSessionId() {
 		return sessionId;
 	}

 	public void setSessionId(String id) {
 	}
 }

This class is ViewScoped so one bean instance will be created for each client session. The current HTTP session ID for this client will be tracked. An instance of the MessageBean is injected so that text can be added as needed.

Currently no Ajax Push is used in the above code, since we will add that further below.

6. Create TextModel.java

Create a new Java class file called TextModel in the package org.icefaces.tutorial.easyajaxpush.model and paste the code below:

TextModel.java
package org.icefaces.tutorial.easyajaxpush.model;

import java.io.Serializable;

public class TextModel implements Serializable {
	private String text;
	private String color;

	public TextModel() {
	}

	public TextModel(String text, String color) {
		this.text = text;
		this.color = color;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String toString() {
		return text;
	}
}

This is a very basic model class that maintains and associates text and color, and is used in the MessageBean to display a list of formatted messages.

7. Deploy the Application

Once the application is built and deployed and running it will look fairly basic. Clicking a color button will refresh the list of messages, since no Ajax Push has been added yet. Ideally we want to be able to open multiple web browsers and see each others color choices immediately through Ajax Push.

8. Adding Ajax Push

Now that the project files are setup and running, our goal is to improve it by adding Ajax Push, which is the main topic of this tutorial. To do this the ICEfaces class org.icefaces.application.PushRenderer will be used. Developers who used older versions of ICEfaces may be familiar with SessionRenderer, which is similar, and is supported as a wrapper for PushRenderer.  If you previously used the ICEfaces 1.x RenderManager you will have to port to the PushRenderer, and the RenderManager and associated classes are not available in ICEfaces 3.

It is also important to understand that the ColorBean is not initialzied until it is first used (it is lazy loaded).  To get around this, so all clients are updated even if they have not click on any buttons, we first output the sessionId to the user, which initializes the bean.

8a. ColorBean Setup

All our interaction with Ajax Push will be done inside the ViewScoped bean called ColorBean.java, which was created using the code above.

First open ColorBean.java and add a constant PUSH_GROUP to represent the name of our push group (explained below, or in detail in the ICEpush documentation):

ColorBean.java
public class ColorBean implements Serializable {
...
private static final String PUSH_GROUP = "colorPage";
...

8b. PushRenderer.addCurrentSession

The next step is to add our current client session to a push group, the name of which is based on the PUSH_GROUP variable added above. Then when Ajax Push requests are sent or received for this push group ICEpush will know to update the page.

Add the following at the top of the constructor (around line 24):

ColorBean.java
PushRenderer.addCurrentSession(PUSH_GROUP);

For a result of:

ColorBean.java
	public ColorBean() {
		PushRenderer.addCurrentSession(PUSH_GROUP);

		FacesContext fcontext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession)fcontext.getExternalContext().getSession(false);
		sessionId = session.getId();
	}

8c. PushRenderer.render

Now when a color button is clicked and the message is added to the list an Ajax Push notification should be sent to any other client sessions in the push group "colorPage" (from our variable PUSH_GROUP).

To do this add the following line of code to the ColorBean.java action method chooseColor, after the addToList call before the return (around line 46):

ColorBean.java
PushRenderer.render(PUSH_GROUP);

For a result of:

ColorBean.java
	public String chooseColor() {
		messageBean.addToList(sessionId, color);

		PushRenderer.render(PUSH_GROUP);

		return null;
	}

Now after a message is added to the list we request an ICEpush render (aka use Ajax Push) via the PushRenderer.

9. Re-Deploy the Application

Re-build and re-deploy the application with the PushRenderer changes.

Open multiple web browsers to the deployed easyAjaxPush application. Now when a color button is clicked in one browser, all other browsers also see the new message. This is thanks to Ajax Push!

An example of how the running application looks:

In future projects that you wish to use ICEpush in, the core two step process explained in detail above of PushRenderer.addCurrentSession and PushRenderer.render is a simple and elegant way to tap into the power and features of Ajax Push!


Tutorial Source Code Downloads

Example Source Notes
Easy Ajax Push project easyAjaxPush source code Basic example project demonstrating how to add Ajax Push to an ICEfaces 3 application.
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

© Copyright 2018 ICEsoft Technologies Canada Corp.