hover animation preload
Different ways to create an object in java

 

1.Create an object using new keyword:

This is the most commonly used method for object creation. to call the constructor to create a new object.

In this approach mainly used for statically creating an object.

for example:


Myobject myobject = new Myobject();

2.Create an object using Class.forName():

In this approach mainly used for to create an object dynamically.

for example:


Myobject myobject = (Myobject) Class.forName("com.shunmuga.sample.Myobject").newInstance();

The above static method returns the class object associated with the class
name. The string className can be supplied dynamically at run time.

3.Create an object using clone():

clone() method available in object class in java

clone is yield a copy of an existing objects ,there are two kinds of cloning  Shallow cloning  and deep cloning.

for example:


Myobject myobject = new Myobject();

/**

* Create an object from already created object

*/

Myobject objectClone =(Myobject) myobject.clone();

 

4.Create an object using deserialization:

Serialization is a process of writing an object to a file or a stream.
deserialization is an way to get back the  object from its serialized form.

for example:


ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);

MyObject object = (MyObject) objectInputStream.readObject(); 
If you find this article is useful to you, dont forget to give your valuable comments. Have a joyous day

 

 

 

 

Java Snippets code for generating PDF using iText

Introduction:

This article specifies a simple Java code snippet for generating PDF using iText jar. we are all familiar with iText is an open source library. It is used to creating and manipulating PDF,RTF and  HTML files with the use of Java code.   iText also support .NET Framework under the name of iTextSharp.

Download the latest iText jar here.

The following snippets of code used to create the pdf document here specify the size and name of the document.


/**
* Create the document and given the name of the document and specify the
* document size like A0 to A9
*/
Document document = new Document(PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\shunmuga\\Desktop" + File.separator + "SamplePicture.pdf"));

The follwing code is used to construct the header and footer of the document.


/**
* Add the header name for the document using the following code
*
*/
HeaderFooter header = new HeaderFooter(new Paragraph("Appache Tomcat"), false);
header.setBorder(Rectangle.NO_BORDER);
header.setAlignment(Element.ALIGN_CENTER);
document.setHeader(header);
/***
* Add the footer name for the document using the following code
*/
HeaderFooter footer = new HeaderFooter(new Phrase("Page No"), false);
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_CENTER);
document.setFooter(footer);

If you want add image in the pdf document using the following  code.


/**
* Add the image in the pdf  document using the following code
*/
File inputFile = new File("tomcat.JPG");
Image img = Image.getInstance(inputFile.getName());
img.setAlignment(Element.ANNOTATION);
img.setIndentationLeft(200);

If you want add  paragraph means using the following  code.


/**
*Add a  paragrah to  the pdf document
*/
String address = " Good year Court, \n Subangjaya, \n Malaysia";
Paragraph paragraph = new Paragraph(address);

If you want construct table in pdf  using the following code.


/**
* The following code explains the construct table in a pdf
*/
PdfPTable datatable = new PdfPTable(5);
PdfPCell cell = new PdfPCell(new Paragraph("No"));
datatable.addCell(cell);
datatable.addCell("Wonders");
datatable.addCell("Country");
datatable.addCell("Data Of Construction");
datatable.addCell("Image");
//Here Specify the column width of the table
int headerwidths[] =
{
5, 12, 12, 12, 12
};

If you want add chunk or phrase in pdf document using the following code.


/**
*The following code is used to add the chunk between the lines of the
* document
*/
Chunk chunk = new Chunk();
chunk.setNewPage();
chunk.setBackground(Color.BLUE);

/**
* Add a  phrase to  the pdf document
*/
String address = "\n Good year Court, \n Subangjaya, \n Malaysia";
Phrase phrase = new Phrase(address);

The following code is used to set the desired font style for header or foooter any paragraph.


/**
* Here specify the font
*/
Font headerFont = FontFactory.getFont(FontFactory.TIMES_ROMAN, 14,
new Color(0, 0, 0));

The following code is used to create hyperlink in pdf document.


/**
*Here creating the hyperlink and specify the font
*/
Anchor anchor = new Anchor("www.shunmuga.com",
FontFactory.getFont(FontFactory.TIMES_ROMAN, 12, Font.UNDERLINE, new Color(0, 0, 255)));

Examples:

Have a look at this following  examples to construct pdf

1.Java Code to Convert PDF Using Itext jar

2.Java Code to construct a table in PDF using iText

If you find this article is useful to you, dont forget to give your valuable comments. Have a joyous day.

Java Code To Get Desktop Path Using Desktop API

Introduction:

This article specifies a simple Java code to open the file or folder  using the Desktop class.It allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.The desktop API mainly for the following purpose.

  1. It supports system’s default browser with a specific Uniform Resource Identifier (URI)
  2. It supports the host system’s default email client
  3. It supports applications to open, edit, or print files associated with those applications

package com.shunmuga.sample;

import java.awt.Desktop;
import java.io.File;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
*
* @author shunmuga
*/
public class DesktopPath
{

private Logger logger = Logger.getLogger(getClass());

private void getOpen(String filePath)
{
try
{

//This check to determine whether the Desktop API is available or not.
if (Desktop.isDesktopSupported())
{
Desktop    desktop = Desktop.getDesktop();
File file = new File(filePath);

/**

* This method is used to open the associated application
* to open a file.
*/

if (file.exists())
{
desktop.open(file);
}
else
{
logger.info("The specified file not found");
}
}
}

catch (Exception e)
{
logger.error("Exception occur while open the file", e);
}
}

static public void main(String[] args)
{
BasicConfigurator.configure();
DesktopPath getDesktopPath = new DesktopPath();
getDesktopPath.getOpen("G:\\Snaps\\DSC03242.JPG");
}
}

1.if you want  to open the file in appropriate application editor using the following code.


/**
* This function is used to open the associated application
* to open a file in appropriate editor.
*/
if (desktop.isSupported(Desktop.Action.EDIT))
{
desktop.edit(file);
}

2.if you want  to print the file  using the following code.


/**
* This method is used to print a file using the
* system default print utility using
* the appropriate comment for the application.
*/
if (desktop.isSupported(Desktop.Action.PRINT))
{
desktop.print(file);
}

3.If you want to open up the specified uri using the following code.


/**
*This function used to open up default browser to display a URI
*/
if (desktop.isSupported(Desktop.Action.BROWSE))
{
URI uri = new URI("www.shunmuga.com");
desktop.browse(uri);
}

If you find this article is useful to you dont forget to give your valuable comments. Have a joyous day.

mport java.awt.Desktop;
import java.io.File;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

/**
*
* @author shunmuga
*/
public class DesktopPath
{

private Logger logger = Logger.getLogger(getClass());

private void getOpen(String filePath)
{
try
{
Desktop desktop = null;
if (Desktop.isDesktopSupported())
{
desktop = Desktop.getDesktop();
File file = new File(filePath);
if (file.exists())
{
desktop.open(file);
}
else
{
logger.info(“The specified file not found”);
}
}
} catch (Exception e)
{
logger.error(“Exception occur”, e);
}
}

static public void main(String[] args)
{
BasicConfigurator.configure();
DesktopPath getDesktopPath = new DesktopPath();
getDesktopPath.getOpen(“G:\\Snaps\\DSC03242.JPG”);
}
}

Java Code to construct a table in PDF using iText

Introduction:

This article specifies a simple Java code to construct a table in PDF using iText jar. we are all familiar with iText is an open source library. It is used to creating and manipulating PDF,RTF and  HTML files with the use of Java code.Download the latest iText jar here.

DataTableBean.java

This class contains the required data to populate the  table value such as wonder, country and the details of the seven wonders construction.


package com.shunmuga.pdfsample;

/**
*
* @author shunmuga
*/
public class DataTableBean
{
private String wonders;
private String country;
private String dateOfConstruction;
private String imagePath;

public DataTableBean()
{
}

/**
* @return the country
*/
public String getCountry()
{
return country;
}

/**
* @param country the country to set
*/
public void setCountry(String country)
{
this.country = country;
}

/**
* @return the wonders
*/
public String getWonders()
{
return wonders;
}

/**
* @param wonders the wonders to set
*/
public void setWonders(String wonders)
{
this.wonders = wonders;
}

/**
* @return the dateOfConstruction
*/
public String getDateOfConstruction()
{
return dateOfConstruction;
}

/**
* @param dateOfConstruction the dateOfConstruction to set
*/
public void setDateOfConstruction(String dateOfConstruction)
{
this.dateOfConstruction = dateOfConstruction;
}

/**
* @return the imagePath
*/
public String getImagePath()
{
return imagePath;
}

/**
* @param imagePath the imagePath to set
*/
public void setImagePath(String imagePath)
{
this.imagePath = imagePath;
}
}

PDFTable.java

This class is used to construct the table contains the following steps

1.First we need to create a document using iText API and specify within a defined page size


Document document = new Document(PageSize.A3.rotate());

2.PdfWriter object to write the content of the pdf  and specify the location  where you want to store


PdfWriter.getInstance(document, new FileOutputStream("C:/Users/shunmuga/Desktop" + File.separator + "wonders.pdf"));

3.Construct the header and footer  using the following code


HeaderFooter footer = new HeaderFooter(new Phrase("Page no: "), true);
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_CENTER);
document.setFooter(footer);
HeaderFooter header = new HeaderFooter(new Paragraph("Seven Wonders Of the World"), false);
header.setBorder(Rectangle.NO_BORDER);
header.setAlignment(Element.ALIGN_CENTER);
document.setHeader(header);

4.Construct the table using the following code


PdfPTable datatable = new PdfPTable(5);
PdfPCell cell = new PdfPCell(new Paragraph("No"));
datatable.addCell(cell);
datatable.addCell("Wonders");
datatable.addCell("Country");
datatable.addCell("Data Of Construction");
datatable.addCell("Image");

Below is the complete code for creating table in pdf


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.shunmuga.pdfsample;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
*
* @author shunmuga
*/
public class PDFTable
{

private List<DataTableBean> dataTableBeanList = new ArrayList<DataTableBean>();

public PDFTable()
{
populateBeanList();
}

/**
* This method is used to populate the data table bean list
*/
private void populateBeanList()
{
DataTableBean dataTableBean = new DataTableBean();
dataTableBean.setWonders("Machu Picchu");
dataTableBean.setCountry("Peru");
dataTableBean.setDateOfConstruction("1460-1470");
dataTableBean.setImagePath("image/Before_Machu_Picchu.jpg");
dataTableBeanList.add(dataTableBean);

dataTableBean = new DataTableBean();
dataTableBean.setWonders("Giza Pyramid Complex");
dataTableBean.setCountry("Egypt");
dataTableBean.setDateOfConstruction("2584-2561 BC");
dataTableBean.setImagePath("image/pyramid.jpg");
dataTableBeanList.add(dataTableBean);

dataTableBean = new DataTableBean();
dataTableBean.setWonders("Taj Mahal");
dataTableBean.setCountry("Agra,India");
dataTableBean.setDateOfConstruction("1630 A.D.");
dataTableBean.setImagePath("image/Taj_Mahal_in_March_2004.jpg");
dataTableBeanList.add(dataTableBean);

dataTableBean = new DataTableBean();
dataTableBean.setWonders("Petra");
dataTableBean.setCountry("Jordan");
dataTableBean.setDateOfConstruction("9 B.C. – 40 A.D.");
dataTableBean.setImagePath("image/PetraMonastery.jpg");
dataTableBeanList.add(dataTableBean);

dataTableBean = new DataTableBean();
dataTableBean.setWonders("Great Wall of China");
dataTableBean.setCountry("China");
dataTableBean.setDateOfConstruction("220 B.C and 1368 – 1644 A.D.");
dataTableBean.setImagePath("image/GreatWallNearBeijingWinter.jpg");
dataTableBeanList.add(dataTableBean);

dataTableBean = new DataTableBean();
dataTableBean.setWonders("Christ the Redeemer");
dataTableBean.setCountry("Brazil");
dataTableBean.setDateOfConstruction("1931");
dataTableBean.setImagePath("image/CorcovadofotoRJ.jpg");
dataTableBeanList.add(dataTableBean);

dataTableBean = new DataTableBean();
dataTableBean.setWonders("Colosseum");
dataTableBean.setCountry("Rom Italy");
dataTableBean.setDateOfConstruction("70 – 82 A.D");
dataTableBean.setImagePath("image/Colosseum_in_Rome,_Italy_-_April_2007.jpg");
dataTableBeanList.add(dataTableBean);
}

private void getGeneratePdfTable()
{
try
{
//Create new instance for docuement and specify the sheet size like A0,A1.... A10
Document document = new Document(PageSize.A3.rotate());
PdfWriter.getInstance(document, new FileOutputStream("C:/Users/shunmuga/Desktop" + File.separator + "wonders.pdf"));

// headers and footers must be added before the document is opened
HeaderFooter footer = new HeaderFooter(new Phrase("Page no: "), true);
footer.setBorder(Rectangle.NO_BORDER);
footer.setAlignment(Element.ALIGN_CENTER);
document.setFooter(footer);

HeaderFooter header = new HeaderFooter(new Paragraph("Seven Wonders Of the World"), false);
header.setBorder(Rectangle.NO_BORDER);
header.setAlignment(Element.ALIGN_CENTER);
document.setHeader(header);

document.open();
document.add(new Paragraph(" "));
//Specify the number of colums
PdfPTable datatable = new PdfPTable(5);
PdfPCell cell = new PdfPCell(new Paragraph("No"));
datatable.addCell(cell);
datatable.addCell("Wonders");
datatable.addCell("Country");
datatable.addCell("Data Of Construction");
datatable.addCell("Image");
//Here Specify the column width of the table
int headerwidths[] =
{
5, 12, 12, 12, 12
};
datatable.setWidths(headerwidths);
datatable.setWidthPercentage(100);
datatable.getDefaultCell().setPadding(5);
datatable.setHeaderRows(1);

datatable.getDefaultCell().setBorderWidth(1);
int i = 1;
for (DataTableBean dataTableBean : dataTableBeanList)
{
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
datatable.addCell(String.valueOf(i));
datatable.addCell(dataTableBean.getWonders());
datatable.addCell(dataTableBean.getCountry());
datatable.addCell(dataTableBean.getDateOfConstruction());
Image img1 = Image.getInstance(dataTableBean.getImagePath());
datatable.addCell(img1);
datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
i++;

}

document.add(datatable);
document.close();
} catch (Exception ex)
{
ex.printStackTrace();
}
}

public static void main(String[] args)
{
PDFTable pDFTable = new PDFTable();
pDFTable.getGeneratePdfTable();

}
}

If you find this article is useful to you, dont forget to give your valuable comments. Have a joyous day.

Sorting the bean list using apache commons bean utils

Introduction:

This article specifies  how to sort the bean list in an efficient way. Nowadays whenever I surf  the net, comparable interface is widely used to sort the bean list. I am very sure its a best approach no doubt in that. In case  if you want to sort the bean list in more than one place of your projects, I feel the code will be redundant. Am I right?

The alternate and the best solution is to use the apache commons bean utils to sort the bean list. In this article, I had given a BeanComparator class used to sort the bean list . In the below example let us use any one of the four properties named (firstName,lastName,address,id) to a ComparableComparator class. Bean class performs two kinds of sorting one is ascending order and the other one is reverse sorting(Descending Order).

Asceding order:

For ascending order, we should give the parameter alone. For instance, if we want sort the parameter “firstName”. We should pass the parameter firstName to the BeanComparator class instance as the below.


BeanComparator beanComparator = new BeanComparator("firstName");
Collections.sort(addressBeanList, beanComparator);

Reverse Order Sorting(Descending Order):

For descending order, we should give the parameter along with the instance of ReverseComparator class. For instance, if we want to sort the parameter “firstName”. We should pass two parameters, such as the  firstName  and the instance of ReverseComparator class to the BeanComparator class as the below.


BeanComparator reverseOrderBeanComparator = new BeanComparator("firstName", new ReverseComparator(new ComparableComparator()));
Collections.sort(addressBeanList, reverseOrderBeanComparator);

Passing “null” to this constructor will cause the BeanComparator to compare objects based on natural order, that is java.lang.Comparable.

downlaod the apache common utils jars

BeanList.java


package com.shunmuga.sample;

/**
*
* @author shunmuga
*/
public class BeanList
{

private String firstName;
private String lastName;
private int id;
private String address;

public BeanList(String firstName, String lastName, int id, String address)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.id = id;
}

/**
* @return the firstName
*/
public String getFirstName()
{
return firstName;
}

/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}

/**
* @return the lastName
*/
public String getLastName()
{
return lastName;
}

/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}

/**
* @return the id
*/
public int getId()
{
return id;
}

/**
* @param id the id to set
*/
public void setId(int id)
{
this.id = id;
}

/**
* @return the address
*/
public String getAddress()
{
return address;
}

/**
* @param address the address to set
*/
public void setAddress(String address)
{
this.address = address;
}
}

Below is the complete code for sorting the bean list.

SampleBeanComparator.java


package com.shunmuga.sample;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ReverseComparator;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author shunmuga
*/
public class SampleBeancomparator
{

private List<BeanList> addressBeanList = new ArrayList<BeanList>();

public SampleBeancomparator()
{
BeanList beanList = new BeanList("Shunmuga", "Krishna", 1, "West");
addressBeanList.add(beanList);
beanList = new BeanList("Laxman", "Guru", 2, "North");
addressBeanList.add(beanList);
beanList = new BeanList("Gift", "Sam", 3, "East");
addressBeanList.add(beanList);
}

/**
* This method is used to sort the address bean list  by ascending order
* using apache commons utils.
*/
private void sort()
{
BeanComparator beanComparator = new BeanComparator("firstName");
Collections.sort(addressBeanList, beanComparator);
System.out.println("----------------Ascending order----------------------");
for (BeanList b : addressBeanList)
{

System.out.print("FirstName:" + b.getFirstName() + " ");
System.out.print("LastName:" + b.getLastName() + " ");
System.out.print("Address:" + b.getAddress() + " ");
System.out.println("Id:" + b.getId());

}
System.out.println("-----------------------------------------------------");
}

/**
* This method is used to sort the address bean list  by descending order
* using apache commons utils.
*/
private void reverseOrderSorting()
{
BeanComparator reverseOrderBeanComparator = new BeanComparator("firstName", new ReverseComparator(new ComparableComparator()));
Collections.sort(addressBeanList, reverseOrderBeanComparator);
System.out.println("---------------Descending order-----------------------");
for (BeanList b : addressBeanList)
{
System.out.print("FirstName:" + b.getFirstName() + " ");
System.out.print("LastName:" + b.getLastName() + " ");
System.out.print("Address:" + b.getAddress() + " ");
System.out.println("Id:" + b.getId());
}
System.out.println("-----------------------------------------------------");
}

public static void main(String[] args)
{
SampleBeancomparator sampleBeancomparator = new SampleBeancomparator();
sampleBeancomparator.sort();
sampleBeancomparator.reverseOrderSorting();
}
}

Output:


----------------Ascending order----------------------
FirstName:Gift LastName:Sam Address:East Id:3
FirstName:Laxman LastName:Guru Address:North Id:2
FirstName:Shunmuga LastName:Krishna Address:West Id:1
-----------------------------------------------------
---------------Descending order-----------------------
FirstName:Shunmuga LastName:Krishna Address:West Id:1
FirstName:Laxman LastName:Guru Address:North Id:2
FirstName:Gift LastName:Sam Address:East Id:3
-----------------------------------------------------

If you find this article is useful to you dont forget to give your valuable comments. Have a joyous day.


Java code to read XML file using JDOM

This article specifies a simple Java code to read the data or contents from the xml file using jdom jar.  JDom is a way to represent an xml document for easy to read and write ,JDOM is an light weight for manipulation,Despite the name similarity its not build on DOM or modeled after DOM. It supports reading and writing a Dom document, SAX events and reduce the complexity to read an xml document.

In the following example, I have specified the code to read the data from the xml file(framework.xml).

framework.xml


<root>
<frameWork>
<name>JSF</name>
<description>JavaServerFaces</description>
</frameWork>

<frameWork>
<name>GWT</name>
<description>Google Web ToolKit</description>
</frameWork>
<frameWork>
<name>Spring</name>
<description>Spring</description>
</frameWork>
<frameWork>
<name>Struts</name>
<description>Apache Struts</description>
</frameWork>
<frameWork>
<name>Wickets</name>
<description>Apache Wicket</description>
</frameWork>
<frameWork>
<name>WebWork</name>
<description>WebWork</description>
</frameWork>
<frameWork>
<name>Seam</name>
<description>Jboss Seam</description>
</frameWork>

</root>

ReadXML.java

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
*
* @author shunmuga
*/
public class ReadXML
{

/**
* This method is used to read the dats from XML file
* @throws JDOMException
* @throws IOException
*/
private void getFrameWorkDetails() throws JDOMException, IOException
{

SAXBuilder builder = new SAXBuilder();
String filePath = "C:\\Users\\shunmuga\\Desktop\\framework.xml";

Document document = (Document) builder.build(new File(filePath));
Element root = document.getRootElement();
List totalRow = root.getChildren("frameWork");
System.out.println("Name:" + "Description");
for (int i = 0; i < totalRow.size(); i++)
{
Element frameWork = (Element) totalRow.get(i);
System.out.println(frameWork.getChildText("name") +
"-" + frameWork.getChildText("description"));
}
}

public static void main(String argS[])
{
try
{
ReadXML readXML = new ReadXML();
readXML.getFrameWorkDetails();
}
catch (JDOMException ex)
{
Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Output

Name:Description
JSF-JavaServerFaces
GWT-Google Web ToolKit
Spring-Spring
Struts-Apache Struts
Wickets-Apache Wicket
WebWork-WebWork
Seam-Jboss Seam

If you find this article is useful to you, dont forget to give your valuable comments. Have a joyous day.

What Java Web Application Frameworks do you use?

There are numerous Java web application frameworks used by the developers. This article is the place where you can share the Java Web Application which you use during your development. I have assessed most of the commonly used Java Web Application Frameworks, kindly choose What Java Web Application Frameworks do you use.

Note: Others kindly remark your framework in the comments.

Enums in JSF

Introduction:

We Professionals know how to use Enums in a Java application, But Enums can also be used in a JSF application. This article clearly explains how to use  Enum effectively in a JSF application.

Importance of enum:

  • Can use same values in more than one place of our project.
  • Adding New values are easy

Lets say if  anyone want to display a value in more than one place, Using Enum is the right option. The reason is Adding new values and changing the existing values can be done in one place so that maintenance is so easy for a JSF application. Here Let us see an example how to populate Enum values in various JSFcomponent like selectOneRadio, selectManyCheckbox, selectOneMenu, selectManyMenu, selectManyListbox and selectOneListbox etc.

Our Example

In our example let us see how same Enums values are reused in several JSF components. Our example contains two java classes. The first one(Sports.java) is used to specify the Enum values and the second one(FavoriteSports.java) is the backing bean for our sample JSP document(favouriteSports.jsp). First let us create Enum class and it contains the following code,

Sports.java

This Enum contains the list of  favourite sports.

package com.shunmuga.test;

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
*
* @author shunmuga
*/
public enum Sports
{

FOOTBALL("Foot Ball"), CRICKET("Cricket"),
TENNIS("Tennis"), HOCKEY("Hockey");

private String favourateSports;

//This map contains the key value pair of sports
private static final Map<String, Sports> favouriteSportsMap = new HashMap<String, Sports>();

/**
* This method is used to put the key and appropriate values an
* favouriteSportsMap
*/
static
{
for (Sports sports : EnumSet.allOf(Sports.class))
{
favouriteSportsMap.put(sports.getName(), sports);
}
}

private Sports(String favourateSports)
{
this.favourateSports = favourateSports;
}

public String getName()
{
return favourateSports;
}

public short shortValue()
{
return (short) ordinal();
}
}

And now let us create the backing bean and it contains the following code,

FavouriteSports.java

This class contains the code to populate the values in the web page.


package com.shunmuga.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.model.SelectItem;

/**
*
* @author shunmuga
*/
public class FavouriteSports
{

private String selctedSports;
private Map<String, Sports> favouriteSportsMap = new HashMap<String, Sports>();
private List<SelectItem> favouriteSportsList = new ArrayList<SelectItem>();

public FavouriteSports()
{
fetchFavouriteSportsMap();
fetchFavouriteSportsList();
}

private void fetchFavouriteSportsMap()
{

for (Sports favouriteSports : Sports.values())
{
favouriteSportsMap.put(favouriteSports.getName(), favouriteSports);
}
selctedSports = Sports.CRICKET.name();
}

private void fetchFavouriteSportsList()
{
favouriteSportsList.clear();
Sports[] sportsArray = Sports.values();
for (Sports sports : sportsArray)
{
System.out.println("sports:" + sports);
favouriteSportsList.add(new SelectItem(sports.getName()));
}
}

/**
* @return the selctedSports
*/
public String getSelctedSports()
{
return selctedSports;
}

/**
* @param selctedSports the selctedSports to set
*/
public void setSelctedSports(String selctedSports)
{
this.selctedSports = selctedSports;
}

/**
* @return the favouriteSportsMap
*/
public Map<String, Sports> getFavouriteSportsMap()
{
return favouriteSportsMap;
}

/**
* @param favouriteSportsMap the favouriteSportsMap to set
*/
public void setFavouriteSportsMap(Map<String, Sports> favuriteSportsMap)
{
this.favouriteSportsMap = favuriteSportsMap;
}

/**
* @return the favouriteSportsList
*/
public List<SelectItem> getFavouriteSportsList()
{
return favouriteSportsList;
}

/**
* @param favouriteSportsList the favouriteSportsList to set
*/
public void setFavouriteSportsList(List<SelectItem> favouriteSportsList)
{
this.favouriteSportsList = favouriteSportsList;
}
}

Next we need to configure faces-config.xml for our example,

faces-config.xml


<faces-config version="1.2"
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-facesconfig_1_2.xsd">
<managed-bean>
<description>Managed bean for FavouriteSports</description>
<managed-bean-name>FavouriteSportsBean</managed-bean-name>
<managed-bean-class>com.shunmuga.test.FavouriteSports</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>

</faces-config>

And finally we need to create a JSP page. Let us name the JSP document as favouriteSports.jsp and it contains the following code


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>

<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h:form >
<rich:panel style="width: 400px">
<f:facet name="header">
<h:outputText value="Favourite Sports"/>
</f:facet>

<h:panelGrid columns="2" cellpadding="5"
cellspacing="5">

<%--selectOneRadio values get from bean --%>

<h:outputLabel value="Favourite Sports:"/>
<h:selectOneRadio value="#{FavouriteSportsBean.selctedSports}">
<f:selectItems value="#{FavouriteSportsBean.favouriteSportsMap}"/>
</h:selectOneRadio>

<%--selectManyCheckbox values get from bean --%>

<h:outputLabel value="Favourite Sports:"/>
<h:selectManyCheckbox value="#{FavouriteSportsBean.selctedSports}">
<f:selectItems value="#{FavouriteSportsBean.favouriteSportsMap}"/>
</h:selectManyCheckbox>

<%--selectOneMenu values get from bean --%>

<h:outputLabel value="Favourite Sports:"/>
<h:selectOneMenu style="position: relative; width: 250px">
<f:selectItems value="#{FavouriteSportsBean.favouriteSportsList}"/>
</h:selectOneMenu>

<%--selectManyMenu values get from bean --%>

<h:outputLabel value="Favourite Sports:"/>
<h:selectManyMenu style="position: relative; width: 250px">
<f:selectItems value="#{FavouriteSportsBean.favouriteSportsList}"/>
</h:selectManyMenu>

<%--selectManyListbox values get from bean --%>

<h:outputLabel value="Favourite Sports:"/>
<h:selectManyListbox style="position: relative; width: 250px">
<f:selectItems value="#{FavouriteSportsBean.favouriteSportsList}"/>
</h:selectManyListbox>

<%--selectOneListbox values get from bean --%>

<h:outputLabel value="Favourite Sports:"/>
<h:selectOneListbox style="position: relative; width: 250px">
<f:selectItems value="#{FavouriteSportsBean.favouriteSportsList}"/>
</h:selectOneListbox>

</h:panelGrid>
</rich:panel>
</h:form>
</body>
</html>
</f:view>

Snap Shot
This is the snap shot of our example

I believe this article useful for, enum usage in JSF component. If you find this article is useful to you, Dont forget to leave your valuable comments. Have a joyous day.

Resizable JSF Components Using PrimeFaces

Introduction

Whenever I surf the net, I used to ponder whether there is any options that allows the end user to resize the components of  a web application developed in JSF. But in all this failed to discover a component like that. But now Primefaces has got the option to resize any components in JSF. Once again I was impressed at the peculiar features of Primefaces which has a resizable component that has the ability to resize all the components of JSF. Even I tried this out in Richfaces Panel, this worked without any conflicts. In this article I am going to explain how to implement a resizable option for the Richfaces panel and data table columns. This would be helpful to see the long data((ie)Wrapped data) in the column of a data table.

Prerequisites

  • IDE – Your favourite IDE
  • Tomcat 6.x/Glassfish/Jboss
  • JDK 1.5 and above

I assume that you had configured the Primefaces in your favourite IDE and now in this article let us see a sample , how to implement the resizable tag for the Richfaces panel  and the data table column.

Data Exporting in JSF Using PrimeFaces

Introduction

In this article we shall learn how to export the jsf data table content from the web page to a pdf, xls, xml and csv format in a JSF application, that may be very useful while generating a report . Now we are going to use a component library named Primefaces, which has more than 70+ ajax powered components that enriches our web application with rich look and feel. So here we are going to invoke a Primefaces component named Data Exporter which is used to export the datas in the web page to a  pdf, xls, xml and csv format. I am damn sure, Primefaces reduces the complexity for the developers while constructing a report for a web application.

Prerequisites

  • IDE – Your favourite IDE
  • Tomcat 6.x/Glassfish/Jboss
  • JDK 1.5 and above

I assume that you had configured the Primefaces in your favourite IDE and now in this article let us learn by a sample “Seven wonders of the world” represented in a datatable and let us see how the datas in the data table are exported  in to a PDF, xls, xml and csv format. First let  us begin by creating a backing bean

Get Adobe Flash player