PrimeFaces Beginner’s Guide book published

I am glad to announce that my second book PrimeFaces Beginner’s Guide is published.

As many of us know PrimeFaces is leading JSF component library for JSF based web applications. This PrimeFaces Beginner’s Guide book targets the Java developers with basic knowledge on JSF and jQuery and covers most of the commonly used PrimeFaces components.

Good news is that PrimeFaces Beginner’s Guide book covers the latest PrimeFaces 4.0 version features such as Client Side Validations (CSV) framework, Dialog Framework, Search Expressions, Sticky Component and many other enhancement as well.

The book contains the following 13 chapters covering various PrimeFaces components:
Chapter 1, Introduction to PrimeFaces, introduces PrimeFaces, along with details on how to install and configure it by creating a simple Hello World application. This chapter also provides an overview of various PrimeFaces features, such as AJAX support, Partial Page Rendering (PPR), and explains Poll and Remote Command components, which come in very handy at times. 
Chapter 2, Introducing Sample Application TechBuzz, provides an overview of the sample application TechBuzz, which we are going to build incrementally throughout the book, and explains what PrimeFaces components will be used for various requirements. This chapter also provides an overall picture on setting up the development environment with all the required software, such as JDK, IDE, database, and so on. 
Chapter 3, Using PrimeFaces Common Utility Components, introduces various ommonly used utility components provided by PrimeFaces, such as Growl, Tooltip, BlockUI, NotificationBar, and so on. This chapter also explains new features introduced in PrimeFaces 4.0, such as Fragment, Sticky, Search Expression Framework, and Dialog Framework. 
Chapter 4, Introducing PrimeFaces Client Side Validation Framework, covers PrimeFaces Client Side Validations (CSV) Framework in detail, explaining how to configure and enable client-side validations, integrating the CSV framework with the Bean Validation API, and extending the CSV framework to support custom JSF Validators/-Converters and custom Bean Validation Annotations. 
Chapter 5, Introducing Text Input Components, covers various input text components such as InputText, InputTextArea, Password, InputMask, Inplace Editor, and Rich Text Editor. This chapter also explains the AutoComplete component in detail, explaining how to use it with POJO support, multiple item selection, and so on.
Chapter 6, Working with Selection Input Components, covers several PrimeFaces selection components, including SelectOneMenu, SelectManyMenu, SelectOneRadio, SelectManyCheckbox, PickList, Multi SelectListbox, and so on. 
Chapter 7, Introducing Advanced Input Components, explains how to work with advanced input components, such as Calendar, Rating, Spinner, and Slider. Readers will also learn about uploading and downloading files using FileUpload and FileDownload components. This chapter also explains how to prevent span and bots using CAPTCHA validation. 
Chapter 8, Working with Data Components, covers various data components, such as DataList, DataGrid, and explains DataTable features in depth, including pagination, sorting, filtering, row/cell editing, and so on. Readers will also learn about exporting DataTable data to Excel, PDF, and XML using the DataExporter component. 
Chapter 9, Introducing Advanced Data Visualization Components, introduces advanced data visualization components, such as Carousel, TagCloud, and Schedule. Readers will also learn about displaying data in a Tree structure using Tree and TreeTable components. 
Chapter 10, Working with Layout Components, explains how to create simple and complex layouts using Panel, PanelGrid, AccordionPanel, TabView, and Layout components, and describes various customization options. This chapter also covers creating workflow-style forms using the Wizard component and Portal-like Layouts using the Dashboard component. 
Chapter 11, Introducing Navigation Components, explains creating different styles of menus using various navigation components, such as Menu, SlideMenu, TieredMenu, Menubar, MegaMenu, TabMenu, and Breadcrumb. 
Chapter 12, Drawing Charts, covers how to visualize data in a graphical format using a variety of chart formats, such as Line, Bar, Pie, and Donut charts. This chapter also introduces how to render charts created by the JFreeChart API. 
Chapter 13, Using PrimeFaces Themes, introduces how to use built-in themes provided by PrimeFaces and how to create custom themes using the online ThemeRoller tool. Readers will also learn about how to dynamically change themes using the ThemeSwitcher component. This chapter also gives a brief overview of various PrimeFaces sibling projects, such as PrimeFaces Extensions, PrimeUI, PrimeFaces Mobile, and PrimeFaces Push. 
The book contains loads of code examples along with decent explanation so that reader will get hands-on experience on most of the commonly used components.
I would like to thank Packt Publishers for giving me an opportunity to write PrimeFaces Beginners Guide book. Especially I would like to thank Joanne Fitzpatrick, Kranti Berde, Ritika Dewani for their continuous support throughout writing process.
Also I would like to thank the reviewers Thomas Andraschko, Mauricio Fenoglio, Sudheer Jonna and Nilesh Namdeo Mali for their great support in catching up mistakes/typos and provided lot of ideas for improving the quality of content. In fact I learned a lot from the reviewers comments 🙂
I would like to say special thanks to Çağatay Çivici (I consider his name as synonym for PASSION) for providing such a great framework to Java community.
I hope readers will enjoy reading this book 🙂

PrimeFaces3 Tutorial : Form Validation Using BeanValidation API(JSR-303)

JSF2 has in-built support for form validations using Bean Validation API(JSR-303).
In my previous article PrimeFaces 3 Tutorial : Introduction & Form Validation , I have explained how to validate forms using JSF tags inside JSF xhtml pages.
Now Let us see how we can validate the forms using HibernateValidator which is reference implementation of JSR-303.

Note: Integrating JSR-303 with JSF2 doesn’t have anything to do with PrimeFaces 3.
But I am planning to write a series of articles on PrimeFaces and JSR-303 integration is a part of it.
Please bear with me. 🙂

Step#1: Add hibernate-validator dependency in pom.xml.

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.0.0.GA</version>
<scope>compile</scope>
</dependency>

Here actually we don’t need to specify validation-api.jar dependency explicitely. hibernate-validator.jar dependency will pull the validation-api.jar as its dependency.

Step#2:
Now let us specify the validation constraints for our Registration Form using Annotations on RegistrationForm.java bean.

package com.sivalabs.pfdemo.mb.ui;

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

public class RegistrationForm
{

private Integer userId;

@NotEmpty(message="UserName is required")
@Size(min=5, max=15, message="UsesrName should be of length from 5 to 15 chars")
private String userName;

@NotEmpty(message="Password is required")
@Size(min=5, max=15, message="UsesrName should be of length from 5 to 15 chars")
private String password;

@NotEmpty(message="FirstName is required")
@Size(min=5, max=15, message="UsesrName should be of length from 5 to 15 chars")
private String firstName;

private String lastName;

@Pattern(regexp="[a-zA-Z0-9]+@[a-zA-Z]+.[a-zA-Z]{2,3}", message="Invalid EmailId")
private String email;
private String phone;
private Date dob;
private String gender;
private List<String> interests = new ArrayList<String>();
private boolean subscribeToNewsLetter;

//setters/getters

}

Step#3:
Now you don’t need to mention about validation constrains in JSF xhtml pages anymore. And you don’t need to configure anything explicitly to tell JSF to validate RegistrationForm.

<!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"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">

<h:head>

</h:head>
<h:body>
<h2>Registration Form</h2>
<h:form>
<p:fieldset legend="Registration Form" widgetVar="regWidget" style="width: 600px;">
<h:panelGrid columns="3" width="550" border="0">
<h:outputLabel value="UserName" />
<p:inputText value="#{registrationBean.registrationForm.userName}" id="userName"/>
<p:message for="userName"/>


<h:outputLabel value="Password" />
<p:password value="#{registrationBean.registrationForm.password}" id="password"/>
<p:message for="password" />

<h:outputLabel value="FirstName" />
<p:inputText value="#{registrationBean.registrationForm.firstName}" id="firstName"/>
<p:message for="firstName" />


<h:outputLabel value="LastName" />
<p:inputText value="#{registrationBean.registrationForm.lastName}" id="lastName"/>
<p:message for="lastName" />

<h:outputLabel value="Email" />
<p:inputText value="#{registrationBean.registrationForm.email}" id="email"/>
<p:message for="email" />

<h:outputLabel value="Phone" />
<p:inputText value="#{registrationBean.registrationForm.phone}" id="phone"/>
<p:message for="phone" />

<h:outputLabel value="DOB" />
<p:calendar value="#{registrationBean.registrationForm.dob}"
id="dob"
converterMessage="Invalid Date"
pattern="dd-MM-yyyy">

</p:calendar>
<p:message for="dob" />

<h:outputLabel value="Gender" />
<h:selectOneRadio id="gender"
value="#{registrationBean.registrationForm.gender}" >
<f:selectItems value="#{registrationBean.genders}"
var="gOp"
itemLabel="#{gOp}"
itemValue="#{gOp}"/>
</h:selectOneRadio>
<p:message for="gender" />


<h:outputLabel value="Interests" />
<p:selectManyCheckbox id="interests"
value="#{registrationBean.registrationForm.interests}"
layout="pageDirection">
<f:selectItems value="#{registrationBean.interests}" var="intrOp"></f:selectItems>
</p:selectManyCheckbox>
<p:message for="interests" />

<p:commandButton value="Register" action="#{registrationBean.register}" ajax="false"></p:commandButton>
</h:panelGrid>
</p:fieldset>

</h:form>
</h:body>
</html>

With these changes your Registration Form will be working same as using JSF validation tags.

References:
http://sivalabs.blogspot.in/2012/01/primefaces-3-tutorial-introduction-form.html
http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html_single/

PrimeFaces 3 Tutorial : Introduction & Form Validation

PrimeFaces is a component library for JSF and has huge component support.
Working with PrimeFaces is very much easy because there is a single jar, no mandatory other dependencies, no mandatory configuration is required.

Ok, in this tutorial I am going to explain how to create a Maven based PrimeFaces project and create a simple registration for and validate the form.
I am using JDK1.6.26 and Tomcat 7.0.32.

Step#1
Create Maven Project and add the following repositories, dependencies in pom.xml

<dependencies>  
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>bluesky</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>

<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2</url>
</repository>
<repository>
<id>prime-repo</id>
<name>Prime Repo</name>
<url>http://repository.primefaces.org</url>
</repository>
</repositories>
<build>
<finalName>primefaces-demo</finalName>
</build>

Step#2

Configure JSF2’s FacesServlet configurtion in web.xml

<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<!--Blusky theme for PrimeFaces -->
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bluesky</param-value>
</context-param>

Step#3

Create RegistrationForm bean.

package com.sivalabs.pfdemo.mb.ui;

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

public class RegistrationForm
{
private Integer userId;
private String userName;
private String password;
private String firstName;
private String lastName;
private String email;
private String phone;
private Date dob;
private String gender;
private List<String> interests = new ArrayList<String>();
private boolean subscribeToNewsLetter;

//setters/getters

}

Create RegistrationBean which is a Managed Bean.

package com.sivalabs.pfdemo.mb;

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import com.sivalabs.pfdemo.mb.ui.RegistrationForm;

@ManagedBean
@RequestScoped
public class RegistrationBean
{
private RegistrationForm registrationForm = null;
private List<String> interests = null;
private List<String> genders = null;

public RegistrationBean()
{
this.interests = new ArrayList<String>();
this.interests.add("Sports");
this.interests.add("Gadgets");
this.interests.add("Politics");
this.interests.add("Technology");

this.genders = new ArrayList<String>();
this.genders.add("Male");
this.genders.add("Female");

}

public String register()
{
System.out.println("register.....");
//store data in DB
System.out.println(this.registrationForm);
return "welcome";//go to welcome.xhtml
}

public RegistrationForm getRegistrationForm()
{
if(this.registrationForm == null){
this.registrationForm = new RegistrationForm();
}
return registrationForm;
}

public void setRegistrationForm(RegistrationForm registrationForm)
{
this.registrationForm = registrationForm;
}

public List<String> getInterests()
{
return interests;
}

public void setInterests(List<String> interests)
{
this.interests = interests;
}

public List<String> getGenders()
{
return genders;
}

public void setGenders(List<String> genders)
{
this.genders = genders;
}

}

Step#4: Create registration.xhtml JSF page.

<!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"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">

<h:head>

</h:head>
<h:body>
<h2>Registration Form</h2>
<h:form>
<p:fieldset legend="Registration Form" widgetVar="regWidget" style="width: 600px;">
<h:panelGrid columns="3" width="550" border="0">
<h:outputLabel value="UserName" />
<p:inputText value="#{registrationBean.registrationForm.userName}"
id="userName"
required="true"
requiredMessage="UserName is required"
validatorMessage="UsesrName should be of length from 5 to 15 chars"
>
<f:validateLength minimum="5" maximum="15" for="userName"></f:validateLength>
</p:inputText>
<p:message for="userName"/>


<h:outputLabel value="Password" />
<p:password value="#{registrationBean.registrationForm.password}"
id="password"
required="true"
requiredMessage="Password is required"
validatorMessage="Password should be of length from 5 to 15 chars"
>
<f:validateLength minimum="5" maximum="15" for="password"></f:validateLength>
</p:password>
<p:message for="password" />

<h:outputLabel value="FirstName" />
<p:inputText value="#{registrationBean.registrationForm.firstName}"
id="firstName"
required="true"
requiredMessage="FirstName is required"
validatorMessage="FirstName should be of length from 5 to 15 chars"
>
<f:validateLength minimum="5" maximum="15" for="firstName"></f:validateLength>
</p:inputText>
<p:message for="firstName" />


<h:outputLabel value="LastName" />
<p:inputText value="#{registrationBean.registrationForm.lastName}"
id="lastName"></p:inputText>
<p:message for="lastName" />

<h:outputLabel value="Email" />
<p:inputText value="#{registrationBean.registrationForm.email}"
id="email"
validatorMessage="Invalid Email">
<f:validateRegex pattern="[a-zA-Z0-9]+@[a-zA-Z]+.[a-zA-Z]{2,3}"></f:validateRegex>
</p:inputText>
<p:message for="email" />

<h:outputLabel value="Phone" />
<p:inputText value="#{registrationBean.registrationForm.phone}"
id="phone"></p:inputText>
<p:message for="phone" />

<h:outputLabel value="DOB" />
<p:calendar value="#{registrationBean.registrationForm.dob}"
id="dob"
converterMessage="Invalid Date"
pattern="dd-MM-yyyy">

</p:calendar>
<p:message for="dob" />

<h:outputLabel value="Gender" />
<h:selectOneRadio id="gender"
value="#{registrationBean.registrationForm.gender}" >
<f:selectItems value="#{registrationBean.genders}"
var="gOp"
itemLabel="#{gOp}"
itemValue="#{gOp}"/>
</h:selectOneRadio>
<p:message for="gender" />


<h:outputLabel value="Interests" />
<p:selectManyCheckbox id="interests"
value="#{registrationBean.registrationForm.interests}"
layout="pageDirection">
<f:selectItems value="#{registrationBean.interests}" var="intrOp"></f:selectItems>
</p:selectManyCheckbox>
<p:message for="interests" />

<p:commandButton value="Register" action="#{registrationBean.register}" ajax="false"></p:commandButton>
</h:panelGrid>
</p:fieldset>

</h:form>
</h:body>
</html>

Step#5:
Now go to http://localhost:8080/primfaces-demo/registration.xhtml

Here key things to note are:
1. We need to add primefaces taglib using xmlns:p="http://primefaces.org/ui"
2. PrimeFaces Command Button/Links bydefault use Ajax submit. So to do non-ajax submit we should use ajax=”false”.
3. To enable autocompletion for <p:> tags, right click on project –> Properties –> ProjectFacests –> Select Java Server Faces 2.0 checkbox and Apply.

In the next article PrimeFaces3 Tutorial : Form Validation Using BeanValidation API(JSR-303)I have explained how to validate the forms using JSR-303 Bean Validation API.

PrimeFaces QuickStart Tutorial-Part1

PrimeFaces is an open source component library for JSF 2.0 with morethan 100 rich components. PrimeFaces is far better than many other JSF component libraries because of the following reasons:

    1. Rich set of UI components (DataTable, AutoComplete, HtmlEditor, Charts etc).
    2. No extra xml configuration is required and there is no required dependencies.
    3. Built-in Ajax based on standard JSF 2.0 Ajax APIs.
    4. Skinning Framework with 25+ built-in themes.
    5. Awesome documentation with code examples.
   
Let us build a sample application using PrimeFaces with the following features:
1. A Login screen which accepts username and password and authenticate the user.
2. Upon successful login user will be shown a User Search screen. Users can search for users by their name.The search results will be displayed in a DataTable with pagination, sorting and filtering support.
3. Upon clicking on a row the user details will be displayed in a form.

First download JSF 2 jars from http://javaserverfaces.java.net/download.html
Place the jsf-api-2.0.3.jar, jsf-impl-2.0.3.jar and jstl-1.0.2.jar jars in WEB-INF/lib folder.
Download PrimeFaces from http://www.primefaces.org/downloads.html.
Place primefaces-2.2.RC2.jar in WEB-INF/lib folder.

Configure FacesServlet in web.xml

<web-app version="2.5">

    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
   
   
        index.jsp
   

       
   
        Faces Servlet
        javax.faces.webapp.FacesServlet
        1
   


   
        Faces Servlet
        *.jsf
   

   
</web-app>

Create faces-config.xml in WEB-INF folder.



    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
   
   

Welcome page index.jsp just forwards to login screen.



Create login.xhtml page.

    

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

   


   


           
           
               
               
               
               
               
           

       

   
   
   


</html>

You can get the blusky theme from PrimeFaces bundle.

Create home.xhtml which contains UserSearchForm, Results dataTable and UserDetails Panel.

	



<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<link type="text/css" rel="stylesheet" href="themes/bluesky/skin.css" />
</h:head>
<h:body>
<center>
<h:form>
<p:panel header="Users Search Form" style="width: 700;">
<h:form>
<h:panelGrid columns="3" cellpadding="2">
<h:outputLabel for="#{userManagedBean.searchUser}" value="UserName"/>
<h:inputText value="#{userManagedBean.searchUser}" label="UserName"></h:inputText>
<h:commandButton type="submit" value="Search" action="#{userManagedBean.searchUser}"></h:commandButton>
</h:panelGrid>
</h:form>
</p:panel>


<p:dataTable var="user" value="#{userManagedBean.searchUsersResults}"
selection="#{userManagedBean.selectedUser}" selectionMode="single"
dynamic="true"
onRowSelectUpdate="userUpdateForm"
onRowUnselectUpdate="userUpdateForm"
rowSelectListener="#{userManagedBean.onUserSelect}"
rowUnselectListener="#{userManagedBean.onUserUnselect}"
paginator="true" rows="5" style="width: 700">
<p:column sortBy="#{user.userId}" filterBy="#{user.userId}">
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText value="#{user.userId}" />
</p:column>
<p:column sortBy="#{user.username}" filterBy="#{user.username}">
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{user.username}" />
</p:column>
<p:column sortBy="#{user.emailId}" filterBy="#{user.emailId}">
<f:facet name="header">
<h:outputText value="Email" />
</f:facet>
<h:outputText value="#{user.emailId}" />
</p:column>
<p:column parser="date" sortBy="#{user.dob}" filterBy="#{user.dob}">
<f:facet name="header">
<h:outputText value="DOB" />
</f:facet>
<h:outputText value="#{user.dob}" >
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:outputText>
</p:column>
</p:dataTable>
<p:panel id="userDetailsPanelId" header="Users Details" style="width: 700;">
<h:panelGrid columns="2" cellpadding="2" id="userUpdateForm" border="0" >
<h:outputLabel for="#{userManagedBean.selectedUser.userId}" value="UserId"/>
<h:inputText value="#{userManagedBean.selectedUser.userId}" style="width: 100;" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.username}" value="Username"/>
<h:inputText value="#{userManagedBean.selectedUser.username}" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.emailId}" value="EmailId"/>
<h:inputText value="#{userManagedBean.selectedUser.emailId}" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.gender}" value="Gender"/>
<h:inputText value="#{userManagedBean.selectedUser.gender}" readonly="true"></h:inputText>

<h:outputLabel for="#{userManagedBean.selectedUser.dob}" value="DOB"/>
<h:inputText value="#{userManagedBean.selectedUser.dob}" readonly="true">
<f:convertDateTime pattern="MM/dd/yyyy" />
</h:inputText>

</h:panelGrid>
</p:panel>
</h:form>
</center>
</h:body>
</html>

Create User.java domain class.

package com.primefaces.sample;


import java.util.Date;

public class User
{
    private Integer userId;
    private String username;
    private String emailId;
    private String phone;
    private Date dob;
    private String gender;
    private String address;
   
    public User()
    {}
    public User(Integer userId, String username, String emailId, String phone,
            Date dob, String gender, String address)
    {
        this.userId = userId;
        this.username = username;
        this.emailId = emailId;
        this.phone = phone;
        this.dob = dob;
        this.gender = gender;
        this.address = address;
    }
    //setter and getters   
}

Create UserService.java which acts as a mock database table.

package com.primefaces.sample;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class UserService
{
    private static final Map<Integer, User> USERS_TABLE = new HashMap<Integer, User>();
    static
    {
        USERS_TABLE.put(1, new User(1, "Administrator", "admin@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(2, new User(2, "Guest", "guest@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(3, new User(3, "John", "John@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(4, new User(4, "Paul", "Paul@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(5, new User(5, "raju", "raju@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(6, new User(6, "raghav", "raghav@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(7, new User(7, "caren", "caren@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(8, new User(8, "Mike", "Mike@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(9, new User(9, "Steve", "Steve@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(10, new User(10, "Polhman", "Polhman@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(11, new User(11, "Rogermoor", "Rogermoor@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(12, new User(12, "Robinhood", "Robinhood@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(13, new User(13, "Sean", "Sean@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(14, new User(14, "Gabriel", "Gabriel@gmail.com", "9247469543", new Date(), "M", "Hyderabad"));
        USERS_TABLE.put(15, new User(15, "raman", "raman@gmail.com", "9000510456", new Date(), "M", "Hyderabad"));
       
    }
    public Integer create(User user)
    {
        if(user == null)
        {
            throw new RuntimeException("Unable to create User. User object is null.");
        }
        Integer userId = this.getMaxUserId();
        user.setUserId(userId);
        USERS_TABLE.put(userId, user);
        return userId;
    }

    public void delete(User user)
    {
        if(user == null)
        {
            throw new RuntimeException("Unable to delete User. User object is null.");
        }
        USERS_TABLE.remove(user.getUserId());
    }

    public Collection<User> getAllUsers()
    {
        return USERS_TABLE.values();
    }

    public User getUser(Integer userId)
    {
        return USERS_TABLE.get(userId);
    }

    public Collection<User> searchUsers(String username)
    {
        String searchCriteria = (username == null)? "":username.toLowerCase().trim();
        Collection<User> users = USERS_TABLE.values();
        Collection<User> searchResults = new ArrayList<User>();
        for (User user : users)
        {
            if(user.getUsername() != null && user.getUsername().toLowerCase().trim().startsWith(searchCriteria))
            {
                searchResults.add(user);
            }
        }
        return searchResults;
    }

    public void update(User user)
    {
        if(user == null || !USERS_TABLE.containsKey(user.getUserId()))
        {
            throw new RuntimeException("Unable to update User. User object is null or User Id ["+user.getUserId()+"] is invalid." );
        }
        USERS_TABLE.put(user.getUserId(), user);
    }
   
    protected Integer getMaxUserId()
    {
        Set<Integer> keys = USERS_TABLE.keySet();
        Integer maxId = 1;
        for (Integer key : keys)
        {
            if(key > maxId)
            {
                maxId = key;
            }
        }
        return maxId;
    }
}

Create UserManagedBean.java

package com.primefaces.sample;


import java.util.Collection;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;

@ManagedBean
@ApplicationScoped
public class UserManagedBean
{
    UserService userService = new UserService();
   
    private String username;
    private String password;
    private String searchUser;
    private Collection<User> searchUsersResults;
    private User selectedUser;
   
    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public String getPassword()
    {
        return password;
    }
    public void setPassword(String password)
    {
        this.password = password;
    }
   
    public User getSelectedUser()
    {
        if(selectedUser == null){
            selectedUser = new User();
        }
        return selectedUser;
    }
   
    public void setSelectedUser(User selectedUser)
    {
        this.selectedUser = selectedUser;
    }
    public Collection<User> getSearchUsersResults()
    {
        return searchUsersResults;
    }
    public void setSearchUsersResults(Collection<User> searchUsersResults)
    {
        this.searchUsersResults = searchUsersResults;
    }
    public String getSearchUser()
    {
        return searchUser;
    }
    public void setSearchUser(String searchUser)
    {
        this.searchUser = searchUser;
    }
   
    public String login()
    {
        if("test".equalsIgnoreCase(getUsername()) && "test".equals(getPassword()))
        {
            return "home";
        }
        else
        {
            FacesContext context = FacesContext.getCurrentInstance();
            context.addMessage("username", new FacesMessage("Invalid UserName and Password"));
            return "login";
        }
    }
   
    public String searchUser()
    {
        String username = (this.searchUser == null)? "":this.searchUser.trim();       
        this.searchUsersResults = userService.searchUsers(username);
        System.out.println(searchUsersResults);
        return "home";
    }
   
    public String updateUser()
    {
        userService.update(this.selectedUser);
        return "home";
    }
   
    public void onUserSelect(SelectEvent event)
    {       
    }
    public void onUserUnselect(UnselectEvent event)
    {
    }
}

That all we need to do. You can run the application and see the rich user interface with blusky theme.

By default we don’t get automcomplete for PrimeFaces tag in Eclipse. To enable AutoComplete,
Go to Window–>Preferences–>General–>ContentTypes
Select JSP and add .xhtml as file association.

You can download the sample as an Eclipse project Here

JSF can be used for several purposes.

Recently I got a wonderful opportunity to work with JSF and I couldn’t stop myself sharing my feelings on JSF with everyone.
By god’s grace till last month i didn’t a chance to work on JSF in my career. But recently i have to work on a project developed in JSF 1.x.

After spending few days on JSF technology I realized that JSF is not only a web framework and we can use it for several purposes.

Below is just a small list:

1. To test the patience and mental strength of a developer.
2. If you are a team lead/manager and you want to take revenge on a team member you can allot him to work on a JSF project.
3. If your client is not satisfied with your company services and ending the relationship with the organization and you are working on the last project for that client. You can use JSF for that project and deliver a useless, unmaintainable junk and waste a lot of clients money in terms of billing.
4. If anybody wants to move out of java or entirely from IT and is postponing that decision then allot him to work on a JSF project. He will move to new career with in 1 week.
5. In future if we want to show how to write stateful component oriented junk we can keep some JSF projects and show them for reference.

I know there are some JSF fans across the world and they might scold me for this post.
If you want to shout at me please shout at me in Error 500: “{2}” Conversion Error setting value ”{0}” for ”{1}” format because this is what JSF barks for whatever wrong thing happens in this world.

GOD, Save the java community from JSF.