Extending PrimeFaces: AJAX

This is the last of a series of posts (Extending PrimeFaces components is the first one, here the second one) with the purpose of explaining how to use PrimeFaces as an API to create new JSF components. Our main focus in this article is to add AJAX listeners to our components. The component that we are going to analyse together is the Switch from StrazzFaces library: a simple wrapper of one of the Drinks Toolkit widgets, used to manage a boolean value.

Component

Lets start, as always, with the component code:

public class Switch extends UIInput implements Widget, ClientBehaviorHolder {

	public static final String COMPONENT_TYPE = "it.strazz.faces.Switch";
	public static final String COMPONENT_FAMILY = "it.strazz.faces.components";
	static final Collection<String> AVAIABLE_TYPES = Collections.unmodifiableCollection(Arrays.asList("rocker", "arc", "side", "circle", "rect", "toggle"));
	static final String DEFAULT_TYPE = "toggle";
	private static final Collection<String> EVENT_NAMES = Collections.unmodifiableCollection(Arrays.asList("change"));

	@Override
	public Collection<String> getEventNames() {
		return EVENT_NAMES;
	}

	@Override
	public String getDefaultEventName() {
		return "change";
	}

	@Override

	public String getFamily() {
		return COMPONENT_FAMILY;
	}

	public String getWidgetVar() {
		return (String) getStateHelper().eval(PropertyKeys.widgetVar, null);
	}

	public void setWidgetVar(String _widgetVar) {
		getStateHelper().put(PropertyKeys.widgetVar, _widgetVar);
	}

	public String getType() {
		return (String) getStateHelper().eval(PropertyKeys.type, DEFAULT_TYPE);
	}

	public void setType(String _widgetVar) {
		getStateHelper().put(PropertyKeys.type, _widgetVar);

	}

	...
}

The principal feature of this component is to implement the ClientBehaviorHolder interface: using this interface we are declaring that this component is capable of managing ClientBehavior objects. A ClientBehavior is an object that represents a client behaviour defined by a script, in a nutshell it represents a <p:ajax/> tag. In the previous code we have implemented two methods: getEventsName and getDefaultEventName. The first one lists the AJAX events that are valid for our component (the event is defined by the event attribute in the <p:ajax/> tag), the second one simply defines the default event (when not specified on the tag). In our case the only supported event is change.

The other methods of the interfaces let us add/read ClientBehaviors, but they are implemented in the class UIComponentBase: the base class of almost all the JSF components.

Renderer

Lets move on to the Renderer code:

public class SwitchRenderer extends CoreRenderer {

	public static final String RENDERER_TYPE = "it.strazz.faces.SwitchRenderer";

	@Override
	public void decode(FacesContext context, UIComponent component) {
		Switch switchComponent = (Switch) component;
		decodeBehaviors(context, switchComponent);

		String submittedValue = (String) context.getExternalContext().getRequestParameterMap().get(switchComponent.getClientId(context) + "_hidden");
		switchComponent.setSubmittedValue(Boolean.parseBoolean(submittedValue));

	}

	@Override

	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {

		Switch switchComponent = (Switch) component;
		encodeMarkup(context, switchComponent);
		encodeScript(context, switchComponent);

	}

	private void encodeScript(FacesContext context, Switch switchComponent) throws IOException {

		String clientId = switchComponent.getClientId();

		String widgetVar = switchComponent.resolveWidgetVar();

		WidgetBuilder wb = getWidgetBuilder(context);



		wb.init("Switch", widgetVar, clientId);

		wb.attr("widgetName", widgetVar);

		wb.attr("type", getSwitchType(switchComponent));

		encodeClientBehaviors(context, switchComponent);

		wb.finish();

	}

	private void encodeMarkup(FacesContext context, Switch switchComponent) throws IOException {

		...

	}

}

As you can notice from the Renderer code, all we have to do to manage the ClientBehaviors is to invoke two methods: encodeClientBehaviors and decodeClientBehaviors. These methods, inherited from the PrimeFaces CoreRenderer, will link the AJAX functions to the JavaScript widget (encode), and will transform the AJAX call into a Java method invocation on the server (decode). Its interesting to notice that we have to write no code for achieving this goal, PrimeFaces gives us a complete out of the box solution.

Widget

The last element that we are going to analyze is the JavaScript widget:

PrimeFaces.widget.Switch = PrimeFaces.widget.BaseWidget.extend({

	init : function(cfg) {

		this._super(cfg);

		this.input = jQuery(this.jqId+"_hidden");
		this.name = cfg.widgetName;
		this.type = cfg.type;

		var that = this;

		
		jQuery(document).ready(function(){

			if(!that.switchComponent){

				that.switchComponent = Drinks.createElement('switch', {"id":that.id+'_switch'});

				that.switchComponent.setAttribute("onchange", "eval(\"PF('" + that.name + "').onchange(this.value);\");");			

			}

	        });

		}
		

	},

	onchange: function(value){

		this.input.val(value === 1);

		if(this.cfg.behaviors && this.cfg.behaviors.change) {

			this.cfg.behaviors.change.call(this.input);

		}

	}

});

To make an AJAX call, the only thing that we have to do is to invoke the right JavaScript function in the behaviour object of our widget. The purpose on the encodeClientBehaviors method its just to populate this object.

Example

Once the component is ready, its usage its similar to any other PrimeFaces component, as we can see in the next example:

<p:outputPanel layout="block" styleClass="container" id="container">

	<div class="row">

		<div class="col-md-2">

			<s:switch value="#{switchBean.value}">

				<p:ajax update="container" />

			</s:switch>

		</div>

		<div class="col-md-10">

			<p>The Lights are #{switchBean.value ? 'On' : 'Off'}!</p>

		</div>

	</div>

</p:outputPanel>

The result (here a live demo) is this:

 

Conclusions

Lets recap the logical flow of the operations needed to add an AJAX listener to our component:

  • For each <p.ajax/> tag inside our component a ClientBehavior instance is created.
  • The renderer create the widget and links each ClientBehavior to a JavaScript function (encode).
  • The widget wait for user interaction and, in case, will invoke the corresponding function.
  • The renderer convert the client event into a server method (decode).

All of these operations needs a very small amount of code. All the hard work its done by PrimeFaces classes.

With this post I finished my little tutorial on how to create new JSF components using PrimeFaces. You can look at the code of this and other components at the StrazzFaces GitHub repository

Author:

Francesco Strazzullo – software architect and one of the committer in the Primefaces Extensions project.

Extending PrimeFaces components

 

The purpose of this post is to show how we can use PrimeFaces base classes to create new custom components. In a nutshell we will see how to extend PrimeFaces. We will do that by developing a simplified version of the PrimeFaces Extensions Analogclock.

Let’s start with the component class:

@FacesComponent(value = AnalogClock.COMPONENT_TYPE)
@ResourceDependencies({
		@ResourceDependency(library = "moment", name = "moment.min.js"),
		@ResourceDependency(library = "primefaces", name = "jquery/jquery.js"),
		@ResourceDependency(library = "raphael", name = "raphael-min.js"),
		@ResourceDependency(library = "primefaces", name = "primefaces.js"),
		@ResourceDependency(library = "strazzfaces", name = "analog-clock.js") })
public class AnalogClock extends UIComponentBase implements Widget {


	public static final String COMPONENT_TYPE = "it.strazz.faces.AnalogClock";
	public static final String COMPONENT_FAMILY = "it.strazz.faces.components";


	public String getFamily() {
		return COMPONENT_FAMILY;
	}


	public void setStartTime(Date _pattern) {
		getStateHelper().put(PropertyKeys.startTime, _pattern);
	}


	public Date getStartTime() {
		return (Date) getStateHelper().eval(PropertyKeys.startTime, new Date());
	}


	public String getMode() {
		return (java.lang.String) getStateHelper().eval(PropertyKeys.mode,"client");
	}


	public void setMode(String _mode) {
		getStateHelper().put(PropertyKeys.mode, _mode);
	}


	public Integer getWidth(){
		return (Integer) this.getStateHelper().eval(PropertyKeys.width,null);
	}


	public void setWidth(Integer width){
		this.getStateHelper().put(PropertyKeys.width, width);
	}


	public String getWidgetVar() {
		return (String) getStateHelper().eval(PropertyKeys.widgetVar, null);
	}


	public void setWidgetVar(String _widgetVar) {
		getStateHelper().put(PropertyKeys.widgetVar, _widgetVar);
	}


	public String resolveWidgetVar() {
		FacesContext context = getFacesContext();
		String userWidgetVar = (String) getAttributes().get("widgetVar");


		if (userWidgetVar != null)
			return userWidgetVar;
		else
			return "widget_"
					+ getClientId(context).replaceAll(
							"-|" + UINamingContainer.getSeparatorChar(context),
							"_");
	}


	protected static enum PropertyKeys {
		width, widgetVar, startTime, mode;
	}
}

The most interesting thing in this component is to be a Widget. All the components that implements this interface will have a JavaScript counterpart. Basically for every AnalogClock instance on the server, a mirror object will exists on the client browser. The only method we need to implement to use this interface is solveWidgetVar. Its purpose is to return the widgetVar of the component, namely the name of the JavaScript variable assigned to our component.

Analyzing the code above you can notice that if you did not manually set a widgetVar to the component (invoking the setWidgetVar method), the value is automatically generated using the clientId. Some of the others attribute of the AnalogClock are:

Name

Description

width

width of the clock in pixel, set ‘auto’ to adjust to the width of the container. The default value is ‘auto’.

mode

‘server’ for using server time, use the client time otherwise.

startTime

time to display when the mode is €˜server€, the default value is current time.

BaseWidget

One of the ResourceDependencies of AnalogClock it’s the file analog-clock.js. This is a resource file and it must be placed in the resources folder of our project, just like in the next picture.

The file must contain the JavaScript definition of the AnalogClock widget. On the client every widget will be instantiated through a constructor function that extends PrimeFaces.widget.BaseWidget.

PrimeFaces.widget.BaseWidget = Class.extend({ 


        init: function(cfg) {
            this.cfg = cfg;
            this.id = cfg.id;
            this.jqId = PrimeFaces.escapeClientId(this.id);
            this.jq = $(this.jqId);


            .....
        },


        ......
    });

The heart of this function is the init method, here a configuration obect and a reference of the main DOM element of the component are memorized. The Class function its created by Jonh Resig author of the book Secrets of the JavaScript Ninja. In this post theres a detailed explanation of the logic behind this pattern.

Lets create PrimeFaces.widget.AnalogClockthat will extend the BaseWidget. We just have to recall to invoke the superinit manually.

PrimeFaces.widget.AnalogClock = PrimeFaces.widget.BaseWidget.extend({
			init : function(cfg) {


				this._super(cfg);


				this.startTime = cfg.time && cfg.mode !== 'client' ? moment(cfg.time) : moment();


				this.colorScheme = cfg.colorScheme || 'standard';


				this.dimensions = new PrimeFaces.widget.AnalogClock.Dimensions(this.cfg.width || this.jq.width());


				this.interval = setInterval((function(self) {
					return function() {
						self.update();
					}
				})(this), 1000);


				this.draw();
			},


			draw : function() {


				this.canvas = Raphael(this.id, this.dimensions.size, this.dimensions.size);


				this.clock = this.canvas.circle(this.dimensions.half, this.dimensions.half, this.dimensions.clock_width);
				this.clock.attr({
					"fill" : PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].face,
					"stroke" :PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].border,
					"stroke-width" : "5"
				})


				this.draw_hour_signs();


				this.draw_hands();


				var pin = this.canvas.circle(this.dimensions.half, this.dimensions.half, this.dimensions.pin_width);
				pin.attr("fill", PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].pin);


				this.update();
			},


			draw_hour_signs: function(){
				var hour_sign;


				for (i = 0; i < 12; i++) {


					var start_x = this.dimensions.half + Math.round(this.dimensions.hour_sign_min_size * Math.cos(30 * i	* Math.PI / 180));
					var start_y = this.dimensions.half + Math.round(this.dimensions.hour_sign_min_size * Math.sin(30 * i * Math.PI / 180));
					var end_x = this.dimensions.half + Math.round(this.dimensions.hour_sign_max_size * Math.cos(30 * i * Math.PI	/ 180));
					var end_y = this.dimensions.half + Math.round(this.dimensions.hour_sign_max_size * Math.sin(30 * i * Math.PI	/ 180));


					hour_sign = this.canvas.path("M" + start_x + " " + start_y	+ "L" + end_x + " " + end_y);
					hour_sign.attr({
						"stroke":PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].hour_signs,
						"stroke-width" : this.dimensions.hour_sign_stroke_width
					});
				}
			},


			draw_hands: function(){


				this.hour_hand = this.canvas.path("M" + this.dimensions.half + " " + this.dimensions.half	+ "L" + this.dimensions.half + " " + this.dimensions.hour_hand_start_position);
				this.hour_hand.attr({
					stroke : PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].hour_hand,
					"stroke-width" : this.dimensions.hour_hand_stroke_width
				});


				this.minute_hand = this.canvas.path("M" + this.dimensions.half + " " + this.dimensions.half	+ "L" + this.dimensions.half + " " + this.dimensions.minute_hand_start_position);
				this.minute_hand.attr({
					stroke : PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].minute_hand,
					"stroke-width" : this.dimensions.minute_hand_stroke_width
				});


				this.second_hand = this.canvas.path("M" + this.dimensions.half + " " + this.dimensions.half	+ "L" + this.dimensions.half + " " + this.dimensions.second_hand_start_position);
				this.second_hand.attr({
					stroke : PrimeFaces.widget.AnalogClock.colorSchemes[this.colorScheme].second_hand,
					"stroke-width" : this.dimensions.second_hand_stroke_width
				});
			},


			update : function() {
				var now = this.startTime;


				this.hour_hand.rotate(30 * now.hours() + (this.startTime.minutes() / 2.5), this.dimensions.half, this.dimensions.half);
				this.minute_hand.rotate(6 * this.startTime.minutes(), this.dimensions.half, this.dimensions.half);
				this.second_hand.rotate(6 * this.startTime.seconds(), this.dimensions.half, this.dimensions.half);


				this.startTime.add('s', 1);
			}


		});

We will omit the draw function because its not the focus of this article. The only thing that we need to know its that it uses the JavaScript library Raphal to draw a clock via HTML5 canvas. This function is a patchwork of various works Ive found on the internet. Its not very complex, you only need to know a little trigonometry. The cfg parameter holds all the parameters of our AnalogClock component, this attributes are used during the draw phase.

Renderer

The purpose of the Renderer is to link the AnalogClock instance on the server with the JavaScript brother on the client. PrimeFaces API make this operation very easy using the WidgetBuilder. This class handles to build and configure a new widget.

@FacesRenderer(componentFamily = AnalogClock.COMPONENT_FAMILY, rendererType = AnalogClockRenderer.RENDERER_TYPE)
public class AnalogClockRenderer extends CoreRenderer {


	public static final String RENDERER_TYPE = "it.strazz.faces.AnalogClockRenderer";


	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		AnalogClock analogClock = (AnalogClock) component;


		encodeMarkup(context, analogClock);
		encodeScript(context, analogClock);
	}


	protected void encodeMarkup(FacesContext context, AnalogClock clock) throws IOException {
		ResponseWriter writer = context.getResponseWriter();


		writer.startElement("div", clock);
		writer.writeAttribute("id", clock.getClientId(), null);
		writer.endElement("div");
	}


	protected void encodeScript(FacesContext context, AnalogClock analogClock) throws IOException {


		String clientId = analogClock.getClientId();
		String widgetVar = analogClock.resolveWidgetVar();


		WidgetBuilder wb = getWidgetBuilder(context);


		wb.init("AnalogClock", widgetVar, clientId);
		wb.attr("mode", analogClock.getMode());
		wb.attr("time",	analogClock.getStartTime() != null ? analogClock.getStartTime().getTime() : null);


		if(analogClock.getWidth() != null){
			wb.attr("width", analogClock.getWidth());
		}


		wb.finish();
	}
}

As you can see our Renderer extends the PrimeFacess CoreRenderer, so that writing a component to the response its enormously simplified task. In this way our code will remain extremely maintainabile.

Example

We can now try our component. In the next example we will create four AnalogClocks: three of the them will display a server time, the last one the client time.

XHTML Page:

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:p="http://primefaces.org/ui"
	xmlns:s="http://it.strazz.faces/ui">
<h:head>
</h:head>
<h:body>
	<h1>StrazzFaces Clock</h1>
	<h:form>
		<p:panelGrid columns="4">
			<h:panelGroup>
				<h1>Rome</h1>
				<s:analogClock
					startTime="#{clockBean.romeTime}"
					width="250"
					mode="server"/>
			</h:panelGroup>
			<h:panelGroup>
				<h1>London</h1>
				<s:analogClock
					startTime="#{clockBean.londonTime}"
					width="250"
					mode="server"/>
			</h:panelGroup>
			<h:panelGroup>
				<h1>New York</h1>
				<s:analogClock
					startTime="#{clockBean.newYorkTime}"
					width="250"
					mode="server"/>
			</h:panelGroup>
			<h:panelGroup>
				<h1>You</h1>
				<s:analogClock width="250" />
			</h:panelGroup>
		</p:panelGrid>
	</h:form>
</h:body>
</html>

Managed Bean:

@ManagedBean
@RequestScoped
public class ClockBean implements Serializable {


	private static final long serialVersionUID = 1L;


	private Date romeTime;
	private Date londonTime;
	private Date newYorkTime;


	@PostConstruct
	public void loadTimes(){
		romeTime = new Date();


		Calendar c = Calendar.getInstance();


		c.setTime(romeTime);
		c.add(Calendar.HOUR, -1);
		londonTime = c.getTime();


		c.setTime(romeTime);
		c.add(Calendar.HOUR, -5);
		newYorkTime = c.getTime();
	}


	public Date getRomeTime() {
		return romeTime;
	}


	public Date getLondonTime(){
		return londonTime;
	}


	public Date getNewYorkTime(){
		return newYorkTime;
	}


}

 

Author:

Francesco Strazzullo – software architect and one of the committer in the Primefaces Extensions project.

Build a Java EE CRUD application from a Database table using NetBeans and Primefaces

In this tutorial we will learn how quickly we can arrange for a CRUD (Create, Read, Update, Delete) Java EE application starting from a Database Table. We will use a mix of technology such as NetBeans IDE, WildFly and JBoss AS 7 as application server and Java EE and PrimeFaces API.

So, the requirements for this tutorial are:

  • A NetBeans 8 environment
  • A JBoss/WildFly application server
  • A relational database

So the starting point will be a Database table named Customer which is defined on a MySQL server:

mysql> desc customer;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| idCustomer | int(11)     | NO   | PRI | NULL    |       |
| Name       | varchar(45) | YES  |     | NULL    |       |
| Address    | varchar(45) | YES  |     | NULL    |       |
| email      | varchar(45) | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+

Now, provided that you have defined the application server through NetBeans’ Services Menu, let’s start creating a sample Web application. Select from the File Menu: New Project and choose to create a Web application

Choose a name and location for your Web application and a package, as shown by the following picture:

Click on Next and choose the target application server. We will choose for this example a JBoss EAP 6 server:

Click on Finish. You will end up with an empty Web project. Let’s start now cooking some Entities. Select from the File menu a New Entity Classes from Database. Our Entity will be based on the Customer table that we have formerly created:

Please note that you need to define a Datasource on the application server in order to be able to Reverse engineer your Database tables into Entities. Click on Next and complete the wizard by specifying the main Project and the package to be used for your Entity:

As you can see, you can automatically have your Named Query defined for your Entity along with the JAXB annotations if required and the Persistence Unit which maps to the Datasource we have installed on the application server.

Here is the Customer Entity which has been created for us by the Entity from database wizard:

@Entity
@Table(name = "customer")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c"),
    @NamedQuery(name = "Customer.findByIdCustomer", query = "SELECT c FROM Customer c WHERE c.idCustomer = :idCustomer"),
    @NamedQuery(name = "Customer.findByName", query = "SELECT c FROM Customer c WHERE c.name = :name"),
    @NamedQuery(name = "Customer.findByAddress", query = "SELECT c FROM Customer c WHERE c.address = :address"),
    @NamedQuery(name = "Customer.findByEmail", query = "SELECT c FROM Customer c WHERE c.email = :email")})
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "idCustomer")
    private Integer idCustomer;
    @Size(max = 45)
    @Column(name = "Name")
    private String name;
    @Size(max = 45)
    @Column(name = "Address")
    private String address;
    // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
    @Size(max = 45)
    @Column(name = "email")
    private String email;

    public Customer() {
    }

    public Customer(Integer idCustomer) {
        this.idCustomer = idCustomer;
    }

    public Integer getIdCustomer() {
        return idCustomer;
    }

    public void setIdCustomer(Integer idCustomer) {
        this.idCustomer = idCustomer;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (idCustomer != null ? idCustomer.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Customer)) {
            return false;
        }
        Customer other = (Customer) object;
        if ((this.idCustomer == null && other.idCustomer != null) || (this.idCustomer != null && !this.idCustomer.equals(other.idCustomer))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.sample.Customer[ idCustomer=" + idCustomer + " ]";
    }
    
}

Done with th Entity, let’s now create a CRUD interface for the Entity using PrimeFaces JSF libraries. Reach again the upper menu and select New JSF Pages from Entity classes. There choose as Entity class the only one which is available right now:

 

Click on Next. In the following screen, you can configure the SessionBean package for the EJB facade that will be created for your application:

Pay attention to the ComboBox that is at the bottom of the screen. There we have selected as JSF template the PrimeFaces libraries. Click on Next, then Finish the wizard. The expected outcome will be a Java EE application which uses an EJB facade to mediate the requests with the Model class, the Customer Entity. We have also a set of JSF pages (Create.xhtml, Edit.xhtml, List.xhtml and View.xhtml) that are used to handle every possible scenario. As last addition, remember to include in your Project library the PrimeFaces library which needs to be bundled into the WEB-INF/lib folder of your application:

That’s all. Deploy your application on the application server and have fun with your CRUD Java EE Web application!

 

HelloWorld Primefaces

This tutorial shows how to get started quickly with Primefaces with a basic Hello World example that will be deployed on WildFly application server. 

This tutorial is broken in two parts: the first one is an hello world example of Primefaces developed using Eclipse and downloading the library manually. The second helloworld example is engineered with Maven so you will just need to configure Primefaces dependencies in it.

HelloWorld Primafaces using Eclipse

Start by downloading the latest stable Primefaces release from http://www.primefaces.org/downloads
There you will find both the Commercial version of Primefaces called PrimeFaces Elite and the Community version. We will download the Community version. Once downloaded create a new Eclipse Dynamic web project:

Next add Primefaces libraries to the project classpath:

Although not mandatory, you can include the JSF facet to your eclipse project which will include some basic JSF configuration and will assist you while coding your JSF views:

Then,  move to the Deployment Assembly option (available from your Project properties) and include to the deploy path the Primefaces jar library:

Check that your web.xml file contains a path for the Faces servlet and a welcome page:

<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
  http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

	<display-name>HelloPrime</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.xhtml</welcome-file>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>
</web-app>

Now we will create a basic view which will just ask as input for a word and return in an output text an anagram for that word. Here is index.xhtml:

<!DOCTYPE html>
<html xmlns="http://www.w3c.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
    <h:form id="jsfexample">
        <p:panelGrid columns="2">
            <f:facet name="header">Anagram maker</f:facet>

            <h:outputLabel for="Word" value="Word" />
            <p:inputText id="Word" value="#{bean.word}" label="Word" />
            <h:outputLabel for="Anagram" value="Anagram" />
            <h:outputText id="Anagram" value="#{bean.anagram}" />
            <f:facet name="footer">

                <p:commandButton action="#{bean.generateAnagram}" update="Anagram"
                    value="Generate anagram" icon="ui-icon-check" style="margin:0" />
            </f:facet>
        </p:panelGrid>
    </h:form>
</h:body>
</html>

And here is the CDI bean that will generate the anagram algorithm:

package com.mastertheboss;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.enterprise.inject.Model;

@Model
public class Bean {
    private String word;
 
    private String anagram;
 
    public void generateAnagram() {
        Random rand = new Random();
 
        List<Character> characters = new ArrayList<Character>();
        for (char c : word.toCharArray()) {
            characters.add(c);
        }
        StringBuilder output = new StringBuilder(word.length());
        while (characters.size() != 0) {
            int randPicker = (int) (Math.random() * characters.size());
            output.append(characters.remove(randPicker));
        }
        this.anagram = output.toString();
    }
 
    public String getAnagram() {
        return anagram;
    }
 
    public void setAnagram(String anagram) {
        this.anagram = anagram;
    }
 
    public String getWord() {
        return word;
    }
 
    public void setWord(String word) {
        this.word = word;
    }
}

Finally, check before deploying that you have included a WEB-INF/beans.xml file in your project for activating CDI. Now deploy your Helloworld applications from the Servers panel (You need JBoss Tools installed in order to do that).


And here is your HelloWorld application in action:


HelloWorld Primafaces using Maven

Following here are the steps for deploying the HelloWorld primefaces application using Maven. Start by creating a project skeleton using the webapp-javaee7 archetype:

mvn -DarchetypeGroupId=org.codehaus.mojo.archetypes -DarchetypeArtifactId=webapp-javaee7 -DgroupId=com.mastertheboss -DartifactId=primefaces -Dversion=1.0 -Dpackage=com.mastertheboss  -Darchetype.interactive=false –batch-mode –update-snapshots archetype:generate 

This will generate a project named HelloPrime that can be opened and edited through Eclipse or NetBeans. Now, include in the src/main/java of your project the only Bean contained in the project and in the src/main/webapp the index.xhtml file along with the web.xml file contained in the first part of this tutorial.
Now, what’s left to do is configuring the dependencies required to build our project:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mastertheboss</groupId>
    <artifactId>primefaces</artifactId>
    <version>10.0.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>WildFly Quickstart: helloworld</name>
    <description>WildFly Quickstarts: Helloworld</description>
    <url>http://wildfly.org</url>

    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- JBoss dependency versions -->

        <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>

        <version.jboss.spec.javaee.7.0>1.0.3.Final</version.jboss.spec.javaee.7.0>

        <!-- other plug-in versions -->
        <version.war.plugin>2.1.1</version.war.plugin>

        <!-- maven-compiler-plugin -->
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>

        <primefaces.version>6.0</primefaces.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.jboss.spec</groupId>
                <artifactId>jboss-javaee-7.0</artifactId>
                <version>${version.jboss.spec.javaee.7.0}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <!-- Import the CDI API, we use provided scope as the API is included in WildFly -->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the Common Annotations API (JSR-250), we use provided scope
            as the API is included in WildFly -->
        <dependency>
            <groupId>org.jboss.spec.javax.annotation</groupId>
            <artifactId>jboss-annotations-api_1.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the JSF API, we use provided scope as the API is included in
            WildFly -->
        <dependency>
            <groupId>org.jboss.spec.javax.faces</groupId>
            <artifactId>jboss-jsf-api_2.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>${primefaces.version}</version>
       </dependency>

    </dependencies>

    <build>
        <!-- Set the name of the WAR, used as the context root when the app
            is deployed -->
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>${version.war.plugin}</version>
                <configuration>
                    <!-- Java EE doesn't require web.xml, Maven needs to catch up! -->
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <!-- WildFly plug-in to deploy the WAR -->
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>${version.wildfly.maven.plugin}</version>
            </plugin>
        </plugins>
    </build>
</project>

As you can see, in terms of dependencies we have included the CDI, JSF and PrimeFaces dependencies. At the bottom of the pom.xml file you can find the WildFly Maven plugin that can be used to manage deployments on WildFly from the Maven shell.
Just deploy your project with:

mvn clean install wildfly:deploy

You can find the source code for this project at: https://github.com/fmarchioni/mastertheboss/tree/master/web/primefaces/helloworld-primefaces

Do you want to right-size your PrimeFaces application into a JAR file without any WildFly installation ? Then check out this tutorial: Package your Primefaces application in a JAR with Thorntail

Develop mobile Java EE applications using Primefaces

In this tutorial we will learn how to develop a simple Web application for Mobile devices using PrimeFaces mobile extension as JSF API.

Today mobile Web traffic is dramatically on the rise, and creating a smooth mobile experience is at the top for every Web master. In spite of slow networks, mobile users expect a more application-like experience such as smooth load experiences, fast and animated page transitions and application-centric error messages. There are several kit and libraries which can be used to develop mobile applications: we will learn how to use PrimeFaces mobile extension which is an UI kit built on the top of jQuery Mobile that can be used to create JSF applications optimized for mobile devices.

Installing PrimeFaces libs and its mobile kit is quite easy: either add to your Web application lib path the latest Community Downloads (http://primefaces.org/downloads.html):

primefaces-4.X.jar
primefaces-mobile-0.9.X.jar

If you are using Maven, all you need is adding the following dependencies to your application:

<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>4.0</version>
</dependency>

<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces-mobile</artifactId>
    <version>0.9.4</version>
</dependency>

Writing your first mobile application

Writing mobile applications is not much different from ordinary application. All you need to know is that a mobile page is a simple xhtml based JSF view that can have of one or more views. A view is a screen in your layout. Each view is declared within a top-level Page container as shown by the following picture:

Each view in turn contain a content element where you place your actual view content. That being said, you can choose two strategies for coding your mobile site: either choose a multi page approach whetre you code each view in a different .xhtml page (Good idea if you have lots of views in your application) or create a single .xhtml page which will contain all your view, like in the following example we will use just two views so we will include them in a single .xhtml file.

The following example application contains three views: the main view which is the navigation screen where you can enter other views. The forms view is a simple form which stores some Property objects in an ArrayList and a datatable view where data is rendered.

Here’s the mobile.xhtml page:

<f:view xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui"
    xmlns:pm="http://primefaces.org/mobile" contentType="text/html"
    renderKitId="PRIMEFACES_MOBILE">

    <pm:page title="Components">


        <!-- Main View -->
        <pm:view id="main">

            <pm:header title="Mobile" swatch="b" />

            <pm:content>

                <p:panelGrid columns="2" styleClass="ui-responsive">

                    <p:outputPanel style="padding-right: 15px">
                        <h:form>
                            <p:dataList type="inset" styleClass="ui-li-custom">
                                <f:facet name="header">Menu</f:facet>
                                <f:attribute name="icon" value="false" />

                                <h:outputLink value="#forms">Form</h:outputLink>
                                <h:outputLink value="#datatable">Table</h:outputLink>

                            </p:dataList>
                        </h:form>
                    </p:outputPanel>

                </p:panelGrid>
            </pm:content>
        </pm:view>

        <!-- Forms -->
        <pm:view id="forms">
            <pm:header title="Forms">
                <f:facet name="left">
                    <p:commandButton value="Home" action="pm:main" />
                </f:facet>
            </pm:header>

            <pm:content>

                <h:form id="jsfexample">
                    <p:panelGrid columns="2">
                        <f:facet name="header">  
               This is a basic form component 
           </f:facet>
                        <h:outputLabel for="key" value="Enter key" />
                        <p:inputText id="key" value="#{manager.key}" />

                        <h:outputLabel for="value" value="Enter value" />
                        <p:inputText id="value" value="#{manager.value}" />

                        <p:commandButton action="#{manager.save}" value="Save"
                            icon="ui-icon-check" style="margin:0"
                            update="@form,:datatableform:mydata" />

                        <h:messages />
                    </p:panelGrid>

                </h:form>
            </pm:content>
        </pm:view>

      <!-- DatatableView -->
        <pm:view id="datatable">
            <pm:header title="DataTable">
                <f:facet name="left">
                    <h:outputLink value="#main">Home</h:outputLink>
                </f:facet>
            </pm:header>
            <pm:content>
                <h:form id="datatableform">
                    <p:dataTable value="#{manager.cacheList}" var="item" id="mydata"
                        rowKey="#{item.key}">
                        <p:column>
                            <f:facet name="header">Key</f:facet>
                            <h:outputText value="#{item.key}" />
                        </p:column>
                        <p:column>
                            <f:facet name="header">Value</f:facet>
                            <h:outputText value="#{item.value}" />
                        </p:column>
                    </p:dataTable>
                </h:form>
            </pm:content>
        </pm:view>

    </pm:page>

</f:view>

And now some explanation to it: at first the Renderkit: PrimeFaces  Mobile  provides  a  Mobile  Renderkit  for  some  standard  JSF  and  core  PrimeFaces Components.  In our example we are using the renderkit named “PRIMEFACES_MOBILE“.

Next, pay attention to how navigation happens between views:

<h:outputLink value="#forms">Form</h:outputLink>

Another interesting thing to notice is how to reference a component which is in another view. In our example, the Save button contained in the form view updates its own form and the datatable named “mydata” contained in the “datatableform”:

<p:commandButton action="#{manager.save}" value="Save" update="@form,:datatableform:mydata" />

In order to see how this example looks like on a mobile, you can download a mobile emulator like Opera Mobile Emulator (http://www.opera.com/it/developer/mobile-emulator) .  Let’s test it simulating a Galaxy SIII. Deploy the application on JBoss AS /Wildfly at first, then let’s enter the mobile.xhtml page:


Here is the form view, where we enter some data:


And finally this is the datatable view where we list the properties entered.

Enjoy mobile applications using Primefaces! Download the sample project from here (Just add the primefaces libraries in your WEB-INF/lib folder)

Primefaces cookbook review

It is with great pleasure that I’m going to review the Prime Faces Cookbook available at Packt bookstore.

Chapter 1 will give you an headstart of PrimeFaces, providing the details on the setup and configuration of PrimeFaces along with the basics of the PrimeFaces AJAX. 
Chapter 2 introduces the PrimeFaces themes and the concepts involved. By the end of this chapter you will be to create your own site theme including some more advanced topics such as the two variants of the theme switcher—stateless versus stateful—finish this chapter.
Chapter 3 is dedicated to Inputs and Selects, showing how to work with the enhanced input and select components available in PrimeFaces.

Chapter 4 is about the rich set of Containers (Panel,Accordion, ScrollPanel, and TabView) which allow grouping of the JSF components.

Chapter 5 Data Iteration Components, covers the basic and advanced features to visualize data with data iteration components provided by PrimeFaces. Such data iteration components are, for instance, DataTable, Tree, and TreeTable.  

Chapter 6 discusses about the endless Menu variations, explains about several menu variations. PrimeFaces’. Readers will face a lot of recipes
that discuss the menus’ structure, configuration options, customizations, and integration with other components.

Chapter 7 discusses about common tasks to be done with Files and Images (uploading/downloading/image capturing, cropping, and more)
 
Chapter 8 explains how the drag-and-drop utilities in PrimeFaces allow you to create draggable and droppable user interfaces efficiently. They abstract developers from dealing with implementation details on the browser level.  

Chapter 9 discusses about creating Charts and Maps, covering the ways to create visual charts with PrimeFaces’ extensive charting features, and create maps based on Google Maps.

Chapter 10 is the “hidden secret” box as it contains lots of miscellaneous recipes, covering AJAX tricks, periodic polling, focus handling, controlling form submission, and many other recipes which every developer will face when moving into a real world context.

At the end of it, I’m pretty satisfied with this book which is a perfect complimentary reading to the official, excellent, documentation; so no surprise that the guys at Packt arranged for a recipe cookbook instead of a standard development guide.

Being at odds with stylesheets, the chapter 2 was a Godsend for me and I really enjoyed creating nice sample skins. I was really satisfied with Chapter 5 which is about the heart of every web application: data visualization and iteration. My only little complain is that I wanted even more of it, maybe with some Java-based examples that render data columns/format dynamically. I did enjoyed a lot the drag and drop chapter -Chapter 8- and the Chapter 10 which brings it all together and explores advanced use cases.  

So in my opinion this book is an excellent, practical, developer-friendly book which will help you to solve a lot of common pitfalls which are common to web developers. All the examples are easy to understand and well documented and in my opinion it is worth a place on the JSF-user book shelf.

You can read here an excerpt from the sample chapter, which is about Drag and Drop.

PrimeFaces tutorial

Do you need to get started quickly with a light, easy to integrate, rich JSF library ? then PrimeFaces might be what you are looking for!

Today there are several JSF libraries available for your Java EE applications (Richfaces, IceFaces). There is no clear winner as every library excel on some points while it can be improved on other points. Leaving to a next article a comparison between these JSF libraries, here I’d like to introduce PrimeFaces.

Here’s why PrimeFaces really impressed me:

 

PrimeFaces is very easy to integrate with your application. Just add primefaces-X.jar and go.

Zero configuration needed in your descriptors.

100+ rich set of JSF components.

Additional PrimeFaces Mobile module features a UI kit for developing mobile web applications.

Full integration with JQuery which allows to leverage lots of jQuery libraries.

Large, vibrant and active user community.

So as you can see there are several good reason to consider seriously using PrimeFaces. Let’s see how to add it to a Web application.

 

At first download Primefaces latest stable library.

Now create a new Web Project and add primefaces-X.jar to your WEB-INF/lib

 

 

Now add a Web page to your application let’s say home.xhtml:


<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">

<h:head>

</h:head>

<h:body>
    <h:form id="jsfexample">
        <p:panelGrid columns="2">
            <f:facet name="header">  
                Basic PanelGrid  
           </f:facet>
            <h:outputLabel for="key" value="Enter key" />
            <p:inputText id="key" value="#{manager.key}" />

            <h:outputLabel for="value" value="Enter value" />
            <p:inputText id="value" value="#{manager.value}" />

            <p:commandButton action="#{manager.save}" update="mydata"
                value="Save" icon="ui-icon-check" style="margin:0" />
            <p:commandButton action="#{manager.clear}" update="mydata"
                value="Delete" icon="ui-icon-cancel" style="margin:0" />

            <h:messages />


        </p:panelGrid>

        <p:dataTable value="#{manager.cacheList}" var="item" id="mydata"
            selectionMode="single" selection="#{manager.selectedProp}"
            rowKey="#{item.key}">
            <p:column>
                <f:facet name="header">Key</f:facet>
                <h:outputText value="#{item.key}" />
            </p:column>
            <p:column>
                <f:facet name="header">Value</f:facet>
                <h:outputText value="#{item.value}" />
            </p:column>
        </p:dataTable>
    </h:form>
</h:body>
</html>

As you can see, all you need to inject PrimeFaces in your web pages is adding the namespace at the top of your page:


<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">

What this simple application does, is storing a set of properties.

Two things to notice:

1) The dataTable object uses the selectionMode and selection attributes to store the elements which are selected from the dataTable. There is a corresponding field in the manager bean which contains our selection.

2) Notice the update attribute in the commandButton. The commandButton is builti-in with AJAX capabilities and the update attribute let you choose which components need update after the AJAX Response.

And here’s the Backing bean:


package com.sample.bean;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;

import com.sample.ejb.SingletonBean;
import com.sample.model.Property;

@ManagedBean(name="manager")
public class PropertyManager {

    @EJB
    SingletonBean ejb;

    ArrayList<Property>  cacheList  = new ArrayList ();

    private Property selectedProp;
    private String key;
    private String value;

    public void save() {
        ejb.put(key, value);
    }

    public void clear() {
        ejb.delete(selectedProp);
    }
    public List getCacheList() {
        return ejb.getCache();
    }

    // Getters and Setters
    
    public Property getSelectedProp() {
        return selectedProp;
    }

    public void setSelectedProp(Property selectedProp) {
        this.selectedProp = selectedProp;
    }
    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

The EJB implementation just stores in memory the Property objects.


package com.sample.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
 
import javax.ejb.Singleton;
 

import com.sample.model.Property;

@Singleton
public class  SingletonBean   {
  
 private  List<Property> cache; 
 
 @PostConstruct
 public void initCache(){
    cache = new ArrayList<Property>();
 }

 public void delete(Property prop){
      this.cache.remove(prop);
 }
 public void put(String key,String value){
     Property p = new Property();
     p.setKey(key);
     p.setValue(value);
  
     this.cache.add(p);
 }
 public List<Property> getCache() {
     return cache;
 }
           


}

For the Sake of brevity, we have not included the Property class which is a simple POJO. (Download the code at the bottom of this article).

 

I have tested this application with JBoss AS 7 which happily runs with Primefaces!

 

Pretty cool isn’t it ??

In the next article about PrimeFaces, I’d like to try the integration with jQuery libraries. Stay tuned!

Download code here