Monday, September 16, 2013

Simple Custom Validator in JSF2

JSF has several built in validators such as <f:validateRegex/>, <f:validateRegex/> etc. But sometimes you may need to create your own validator. This tutorial will teach you to create your own validator with your own logic.
  Assume that you have a text box in your web page. You need to force the user to enter a text starts with letter 'A'. Following example shows how to do it.

This is the JSF 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">
<h:head></h:head>
<body>
  <h:form>
    <h:inputText id="txt1">
<f:validator validatorId="myValidator"/>
    </h:inputText>
    <h:message for="txt1" style="color:red" />
    <br/>
    <h:commandButton value="Click Me" />
  </h:form>
</body>
</html>

Note that in above page we have added a <h:message/> to display the error message. This is not a must.

Following is out validator class. Validator class should implement the javax.faces.validator.Validator and its validate() method. We should write our logic so that this method throws javax.faces.validator.ValidatorException if the validation failed.

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("myValidator")
public class MyValidator implements Validator {
  @Override
  public void validate(FacesContext ctx, UIComponent comp, Object val)
      throws ValidatorException {
    if(!val.toString().startsWith("A")) {
      FacesMessage msg = new FacesMessage("Please enter a value starts with 'A'");
      throw new ValidatorException(msg);
    }
  }
}

Now run the project and go to the page. Enter a text which doesn't start with 'A' and click the button. A message should be displayed as below.


Thursday, September 5, 2013

How to Read and Write to a Property File In Java -Simple example

In java.util package there is a class called Properties which easily allow you to do read and write operations with Property files. The get() method reads from the file and the store() method writes to the file. If the property is already available in the file, the value will be overridden. Using this class is very simple.

First of all you have to initialize the Properties object by loading a ".properties" file.

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;

  public PropertyTest() {
    initProperties();
  }

  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Note the properties.load() method in above code. That method loads the existing properties to properties Object.

Now your properties object is ready to use. You can save or load data now.
Below code add a property called "testProperty" to the file.
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }


Note that we have used the properties.store() method to save the value.

In below method you can see how to retrieve data from file.
  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }

Note that if the property does not exist in the file it returns null.
That is all.

The following is a full working code.
package testing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;
 
  public PropertyTest() {
    initProperties();
  }
 
  public static void main(String[] args) {
    initProperties();
    addProperty();
    readProperty();
  }
 
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }

  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }
 
 
  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Primefaces Pie Chart Example

It is very easy to create charts with Primefaces. In following example you will see how to add a pie chart to your application within minutes.
☞Remember you should have Primefaces jar added in to your project before continue.
    You can download the latest version of Primefaces from below link.
    http://www.primefaces.org/downloads.html

We use <p:pieChart/> component to add the chart to out xhtml page. So our page will look like this.

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

<h:head></h:head>
<body>
    <p:pieChart title="Sales" value="#{chartBean.pieModel}" legendPosition="w"
        id="salesChart" style="width:350px;height:300px" />
</body>
</html>


Our JSF managed bean is this. Look that our getPieModel method returns a PieChartModel object. In our xhtml page the "value" attribute of <p:pieChart/> component is bound to this method.

import javax.faces.bean.ManagedBean;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "chartBean")
public class ChartBean {
    public PieChartModel getPieModel() {
PieChartModel pieModel = new PieChartModel();
        pieModel.set("Item 1", 10);
        pieModel.set("Item 2", 12.5);
        pieModel.set("Item 3", 30);
        pieModel.set("Item 4", 18);
        return pieModel;
    }
}

Now run the application and go to the page. You will get an output like below.

Wednesday, September 4, 2013

Add a JFreeChart Pie Chart to a JSF Page

JFreeChart is an open-source java library which can be used to create interactive charts of various types. It is widely used in java swing applications. It has the capability to export the generated chart as an image. We can use this ability to use this to display the chart as an image in a JSF page.

☞ JFreeChart is distributed under the LGPL license and so you can use it in your own project without
    publishing your source code.

In this example you will learn to add a JFreeChart chart to your JSF page. You need RichFaces added to your JSF project.

☯ Go to the download page of JFreeChart website to download JFreeChart libraries.

☯ Extract the zip file and open the lib folder. You will see several libraries inside the folder. Just 
    add jcommon-1.0.18.jar and jfreechart-1.0.15.jar to your project.

☯ Now you are ready to use JFreeChart with your project.

☯ Create your JSF managed bean as below.
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.imageio.ImageIO;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

@ManagedBean(name = "chartDemo")
public class ChartDemo {
  public void drawChart(OutputStream out, Object data) throws IOException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Item1", 10);
    dataset.setValue("Item2", 15);
    dataset.setValue("Item3", 8);
    dataset.setValue("Item4", 12.5);
    dataset.setValue("Item5", 30);
    JFreeChart chart = ChartFactory.createPieChart("Sales", dataset, true, true, Locale.ENGLISH);
    BufferedImage bufferedImage = chart.createBufferedImage(300, 300);
    ImageIO.write(bufferedImage, "gif", out);
  }
}

☯ We are going to use the Richfaces <a4j:mediaOutput> tag to show the output. So your xhtml
     page will looks like this.

<!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:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich">

<h:head></h:head>
<body>
    <rich:panel>
        <a4j:mediaOutput style="width:200px;height:200px;" element="img"
  cacheable="false" session="true" createContent="#{chartDemo.drawChart}"
     mimeType="image/gif" />
    </rich:panel>
</body>
</html>

That is all. Run the project and you will see an output like below.


















Note:-
This note is not relative to JFreeChart. But if you are using eclipse and if you got an error like below when you try to run your project it means your JFreeChart libraries are not added to your war file.
java.lang.ClassNotFoundException: org.jfree.data.general.PieDataset from [Module "deployment.RF1.war:main" from Service Module Loader]

To include these files in final deployment do following.
Right click the project ⇨ Properties ⇨ Deployment Assembly ⇨ Add ⇨ Java build path entries
Now select the  jcommon-1.0.18.jar and jfreechart-1.0.15.jar and click Finish. Then click Ok  to close the properties window. Now your deployment will work.