Sunday, September 26, 2010

Tags in JSF

Basically there are two kinds of  tags in JSF.
JSF Core & HTML Tags
Today we will see different  attributes in JSF HTML and Core Tags

JSF HTML Tags :

  • column                              creates column in a dataTable
  • commandButton                creates button
  • commandLink                   creates link that acts like a pushbutton
  • dataTable                         creates a  table control
  • form                                 creates a form
  • graphicImage                    displays an image
  • inputHidden                      creates hidden field
  • inputSecret                       creates input control for password
  • inputText                          creates  text input control (single line)
  • inputTextarea                    creates  text input control (multiline)
  • message                           displays the most recent message for a component
  • messages                          displays all messages
  • outputFormat                    creates  outputText, but formats compound messages
  • outputLabel                      creates label 
  • outputLink                        creates anchor
  • outputText                        creates single line text output
  • panelGrid                         creates html table with specified number of columns
  • panelGroup                      used to group other components where the specification requires one child element
  • selectBooleanCheckbox   creates checkbox
  • selectManyCheckbox       creates set of checkboxes
  • selectManyListbox           creates multiselect listbox
  • selectManyMenu              creates multiselect menu
  • selectOneListbox              creates single select listbox
  • selectOneMenu                creates single select menu
  • selectOneRadio                creates set of radio buttons 

JSF CORE Tags: 

  • f :view                                 Creates the top-level view
  • f:subview                             Creates a subview of a view
  • f:attribute           Adds an attribute  to a component
  • f:param                                Constructs a parameter component
  • f:converter            Adds an arbitrary converter to a component
  • f:converterDateTime      Adds a datetime converter to a component
  • f:converterNumber      Adds a number converter to a component
  • f:actionListener          Adds an action listener to a component
  • f:valueChangeListener     Adds a valuechange listener to a component
  • f:validator             Adds a validator to a component
  • f:validateDoubleRange    Validates a double range for a component’s value
  • f:validateLength         Validates the length of a component’s value
  • f:validateLongRange      Validates a long range for a component’s value
  • f:facet                 Adds a facet to a component
  • f:loadBundle            Loads a resource bundle, stores properties as a Map
  • f:selectitems            Specifies items for a select one or select many component
  • f:selectitem             Specifies an item for a select one or select many component 
  • f:verbatim              Adds markup to a JSF page

Saturday, September 25, 2010

Hibernate example to insert data into database

This is an simple hibernate example to insert records into database.In this i will be explaining you how to create a new project Eclipse IDE.
Steps for starting a new project in Eclipse IDE
1)File-->New-->Project

2) Select javaproject and click next
3) Click finish

4) Click No
5) Right click src folder and create package subin
6) Inside subin package create two java classes Insertion.java and InsertionDetails.java
Insertion.java
package subin;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class Insertion {

/**
* @subinsuresh
*/
public static void main(String[] args) {
Session session = null;

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
org.hibernate.Transaction tx = session.beginTransaction();

//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
InsertionDetails details = new InsertionDetails();
details.setId(1);
details.setFirstName("Subin");
details.setLastName("Suresh");
details.setAddress("xyz");
session.save(details);
System.out.println("Done");
tx.commit();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
session.flush();
session.close();
}
}
}
InsertionDetails.java
package subin;

public class InsertionDetails {
private String firstName;
private String lastName;
private String address;
private long id;



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

public String getAddress() {
return address;
}

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

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


/**
* @param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}

/**
* @param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}

/**
* @return ID Returns ID
*/
public long getId() {
return id;
}

/**
* @param l Sets the ID
*/
public void setId(long l) {
id = l;
}
}
7) Code for  hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.username">web_test1</property>
<property name="hibernate.connection.password">web_test1</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="hibernate.hbm.xml" />
</session-factory>
</hibernate-configuration>
8) Code for  hibernate.hbm.xml 
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="subin.InsertionDetails" table="INSERTIONTABLE">
<id name="id" type="long" column="ID">
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME"/>
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="address">
<column name="Address"/>
</property>
</class>
</hibernate-mapping>

Note: we dont have to create table manually it will be created  automatically in the database.In hibernate.hbm.xml we have specified class name and table name so it maps elements in InsertionDetails.java with column name in database. In this  example we have given
<id name="id" type="long" column="ID">
<generator class="assigned"/>
</id>
to make  id is the primary key.so we cannot insert more than one record with same id value
to prevent that we use class="increment".
9) We need to add necessary jar file otherwise it will give reference problem.To solve this right click project--> properties Add External Jar as shown in the figure below and click Ok.


9 ) Run the project as shown below


 10) You will get following result in console and one row will be inserted to INSERTIONTABLE.

Thursday, September 23, 2010

Server Side Numeric Validator

Few days back i discussed JavaScript function to restrict input to numeric.
Today we will see Server Side Numeric Validator for JSF you can also see AlphaNumeric Validator in JSF  and Server Side Date Validator 
Steps for creating Numeric Validator
1) Create numeric.jsp file
numeric.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="jc" uri="http://jsf-components" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%--
This file is an entry point for JavaServer Faces application.
--%>
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<h:form >
<jc:AlertMessage />
<h:panelGroup>
<h:outputText id="lb_No"value="Label.:" />
<h:inputText id="tf_NO" autocomplete="off" binding="#{numeric.tf_NO}" >
<f:validator validatorId="onlyNum"/>
<f:validateLength minimum="1" maximum="6"/>
</h:inputText>
<h:commandButton id="cb_save" value="Save" action="#{numeric.bt_SAVEActionPerformed}" > </h:commandButton>
</h:panelGroup>
</h:form>
</body>
</html>
</f:view>
------------------------------------------------------------------------------------------------------------------------------
2) Create a package subin and inside subin package create two javaclass files (Numeric.java and OnlyNumericValidator.java)
Numeric.java

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

import javax.faces.component.html.HtmlInputText;

/**
*
* @author SubinSuresh
*/
public class Numeric {

public void bt_SAVEActionPerformed() {
System.out.println("Debug bt_SAVEActionPerformed");
}
private HtmlInputText tf_NO =new HtmlInputText();

/**
* @return the tf_NO
*/
public HtmlInputText getTf_NO() {
return tf_NO;
}

/**
* @param tf_NO the tf_NO to set
*/
public void setTf_NO(HtmlInputText tf_NO) {
this.tf_NO = tf_NO;
}
}
--------------------------------------------------------------------------------------------------------------------------
OnlyNumericValidator.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package subin;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.html.HtmlInputText;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
*
* @author SubinSuresh
*/
public class OnlyNumericValidator implements Validator {

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
String compValue = null;
boolean flag = false;
if (component != null && component instanceof HtmlInputText) {
compValue = (String) ((HtmlInputText) component).getSubmittedValue();
} else if (component != null && component instanceof HtmlInputTextarea) {
compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
}
if (compValue != null && !compValue.equalsIgnoreCase("")) {
flag = compValue.matches("[0-9]*");
if (!flag) {
if (component instanceof HtmlInputText) {
((HtmlInputText) component).setTitle("Only numbers are allowed here");
((HtmlInputText) component).setSubmittedValue("");
} else if (component instanceof HtmlInputTextarea) {
((HtmlInputTextarea) component).setTitle("Only numbers are allowed here");
} else if (component instanceof HtmlSelectOneMenu) {
((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
}
throw new ValidatorException(new FacesMessage("Only numbers are allowed here"));
}
}
}
}
-------------------------------------------------------------------------------------------------------------------------
3)Mapping in faces-config.xml file
<managed-bean>
<managed-bean-name>numeric</managed-bean-name>
<managed-bean-class>subin.Numeric</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<validator>
<validator-id>onlyNum</validator-id>
<validator-class>subin.OnlyNumericValidator</validator-class>
</validator>


JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

Wednesday, September 22, 2010

Make buttons sexier in your site

Sexy Buttons is a very good framework for creating some awesome buttons. These buttons can surely grab attention.


The data points/features these buttons offer  are as follows:

  • The underlying HTML can use either <button> or <a> elements.
  • They are dynamic and shrink/expand to fit their text labels.
  • There are four states: normal, hover/focus, active, and disabled.
  • The labels can include icons. Use one of the 1000+ included Silk icons or use your own. Icons are specified via HTML class attribute.
  • They use the sliding doors CSS technique for increased performance.
  • They support different skins by simply changing an HTML class attribute.
  • A layered Photoshop template is provided to assist in creating new skins.
  • Easy to implement.
  • No Javascript required.
Usage
  1. Download sexy button from here and upload it to your server.
  2. Add link to the style sheet  SexyButtons/sexybuttons.css” type=”text/css” />
  3. Now just admire the buttons.

    Creating System Recovery Disk in Windows 7

    Windows 7 comes with an inbuilt tool to  create a system repair disc. By using system repair disc you can recover your computer from any major issue. To create the disc you need a blank CD/DVD.
    If you have Windows installation disc then you might not need this disc because you can use the installation disc as a repair disc but it is advisable that you should make one disc as a backup copy. It will help you in case you lose your installation disc. Here are the steps to create a disc.
    1. Insert a blank CD/DVD inside the DVD drive.
    2. Click on “Start” button and type system repair disc inside the search box.
    3. Click on the result.

    4. It will open the “Create a system repair disc” window. Select the drive from the drop down and click on “Create disc” button.

    5. It will start the disc creation process. You can see the progress on the progress bar. It will take some time to create the disc.

    That’s it. Your disc is ready. Now you can use it anytime when any major issue occur inside your Windows 7 computer or your computer fails to start.

    First Look at the New Indian Coin

    Tuesday, September 21, 2010

    Server Side Address Validator

    In my last post i wrote  Server Side Date Validator today we will see Server Side Address Validator
    Steps for creating Server Side Address Validator
    1) Create address.jsp file
    address.jsp

    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
    <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
    <%@taglib prefix="jc" uri="http://jsf-components" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%--
    This file is an entry point for JavaServer Faces application.
    --%>
    <f:view>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>JSP Page</title>
    </head>
    <body>
    <h:form >
    <jc:AlertMessage />
    <h:panelGroup>
    <h:outputText id="lb_No"value="Address.:" />
    <h:inputText id="tf_NO" autocomplete="off" binding="#{address.tf_NO}" >
    <f:validator validatorId="addressValidator"/>
    <f:validateLength minimum="10" maximum="30"/>
    </h:inputText>
    <h:commandButton id="cb_save" value="Save" action="#{address.bt_SAVEActionPerformed}" > </h:commandButton>
    </h:panelGroup>
    </h:form>
    </body>
    </html>
    </f:view>
    -------------------------------------------------------------------------------------------------------
    2) Create a package subin and inside subin package create two javaclass files (Address.java and AddressValidator.java)
    Address.java
     /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package subin;

    import javax.faces.component.html.HtmlInputText;

    /**
     *
     * @author SubinSuresh
     */
    public class Address {

        public void bt_SAVEActionPerformed() {
            System.out.println("Debug bt_SAVEActionPerformed");
        }
        private HtmlInputText tf_NO = new HtmlInputText();

        /**
         * @return the tf_NO
         */
        public HtmlInputText getTf_NO() {
            return tf_NO;
        }
        /**
         * @param tf_NO the tf_NO to set
         */
        public void setTf_NO(HtmlInputText tf_NO) {
            this.tf_NO = tf_NO;
        }
    }
    -------------------------------------------------------------------------------------------------------
    AddressValidator.java
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package subin;

    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.component.html.HtmlInputText;
    import javax.faces.component.html.HtmlInputTextarea;
    import javax.faces.component.html.HtmlSelectOneMenu;
    import javax.faces.context.FacesContext;
    import javax.faces.validator.Validator;
    import javax.faces.validator.ValidatorException;

    /**
     *
     * @author subin_s
     */
    public class AddressValidator implements Validator {

        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            String compValue = null;
            boolean flag = false;
            if (component != null && component instanceof HtmlInputText) {
                compValue = (String) ((HtmlInputText) component).getSubmittedValue();
            } else if (component != null && component instanceof HtmlInputTextarea) {
                compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
            }
            if (compValue != null && !compValue.equalsIgnoreCase("")) {
                flag = compValue.matches("[a-zA-Z 0-9/.&-,]*");
            }
            if (!flag) {
                if (component instanceof HtmlInputText) {
                    ((HtmlInputText) component).setTitle("No special symbols are allowed here");
                } else if (component instanceof HtmlInputTextarea) {
                    ((HtmlInputTextarea) component).setTitle("No special symbols are allowed here");
                } else if (component instanceof HtmlSelectOneMenu) {
                    ((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
                }
                throw new ValidatorException(new FacesMessage("Characters you have entered are not allowed here"));
            }
        }
    }
    -----------------------------------------------------------------------------------------------------------
    3)Mapping in faces-config.xml file
    <managed-bean>
    <managed-bean-name>address</managed-bean-name>
    <managed-bean-class>subin.Address</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <validator>
    <validator-id>addressValidator</validator-id>
    <validator-class>subin.AddressValidator</validator-class>
    </validator>

     Note: In  AddressValidator.java we can allow any number character by keeping in regular expression compValue.matches("[a-zA-Z 0-9/.&-,]*")
     

    Monday, September 20, 2010

    Server Side Date Validator

    Steps for creating ServerSide Date Validator
    1) Create datevalidate.jsp file
    datevalidate.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
    <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
    <%@taglib prefix="jc" uri="http://jsf-components" %>
    <%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
    <%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

    <%--
    This file is an entry point for JavaServer Faces application.
    --%>
    <f:view>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>JSP Page</title>
    </head>
    <body>
    <h:form >
    <jc:AlertMessage />
    <h:panelGroup>
    <h:outputText id="lb_No"value="EnterDate.:" />
    <rich:calendar id="dc_SOLD_ON" binding="#{validate.dc_SOLD_ON}" inputStyle="font-size:10pt;width:55px;height:20px"datePattern="dd-MM-yyyy" >
    <f:validator validatorId="dateValidator"/>
    </rich:calendar>
    <h:commandButton id="cb_save" value="Save" action="#{validate.bt_SAVEActionPerformed}" > </h:commandButton>
    </h:panelGroup>
    </h:form>
    </body>
    </html>
    </f:view>
    ---------------------------------------------------------------------------------------------------------
    2) Create a package subin and inside subin package create two javaclass files (DateValidate.java and DateValidator.java)
    DateValidate.java

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

    import org.richfaces.component.html.HtmlCalendar;
    /**
    *
    * @author SubinSuresh
    */
    public class DateValidate {
    public void bt_SAVEActionPerformed() {
    System.out.println("Debug bt_SAVEActionPerformed");
    }
    private HtmlCalendar dc_SOLD_ON= new HtmlCalendar();
    /**
    * @return the dc_SOLD_ON
    */
    public HtmlCalendar getDc_SOLD_ON() {
    return dc_SOLD_ON;
    }
    /**
    * @param dc_SOLD_ON the dc_SOLD_ON to set
    */
    public void setDc_SOLD_ON(HtmlCalendar dc_SOLD_ON) {
    this.dc_SOLD_ON = dc_SOLD_ON;
    }
    }
    --------------------------------------------------------------------------------------------------------------------------
    DateValidator.java

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

    import java.util.Date;
    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.validator.Validator;
    import javax.faces.validator.ValidatorException;
    import org.richfaces.component.html.HtmlCalendar;

    /**
    *
    * @author SubinSuresh
    */
    public class DateValidator implements Validator {

    public String DATE_FORMAT = "dd-MM-yyyy";
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    System.out.println("Debug Inside DateValidator" + ((HtmlCalendar) component).getSubmittedValue());
    String date = (String) ((HtmlCalendar) component).getSubmittedValue();
    try {
    Date dt = converStringToDate(date);
    System.out.println("Debug Inside dt " + dt);
    } catch (Exception ex) {
    ex.printStackTrace();
    ((HtmlCalendar) component).setSubmittedValue("");
    throw new ValidatorException(new FacesMessage("Invalid Date"));
    }
    }
    /**
    * Convert String to Date
    * @param dateString
    * @return
    */
    public Date converStringToDate(String dateString) {
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
    java.util.Date dt = null;
    try {
    dt = sdf.parse(dateString);
    } catch (java.text.ParseException p) {
    System.out.println(p.toString());
    }
    return dt;
    }
    }
    ------------------------------------------------------------------------------------------------------------------
    3)Mapping in faces-config.xml file
    <managed-bean>
    <managed-bean-name>validate</managed-bean-name>
    <managed-bean-class>subin.DateValidate</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <validator>
    <validator-id>dateValidator</validator-id>
    <validator-class>subin.DateValidator</validator-class>
    </validator>


    Sunday, September 19, 2010

    Scrollable datatable in JSF

    Today we will see one of  the important and useful features of  JSF Framework Scrollable datatable.
    This is very useful to improve look of you web page.When we click on DisplayDetails button table will be populated.
    Steps for creating Scrollable datatable.
    1)Create datatable.jsp file
    datatable.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
    <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%--
    This file is an entry point for JavaServer Faces application.
    --%>
    <f:view>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>JSP Page</title>
    </head>
    <body>
    <h:form >
    <jc:AlertMessage />
    <h:panelGroup>
    <h:commandButton id="cb_save" value="Display Details" style="position:absolute;left:490px;" action="#{scroll.bt_SAVEActionPerformed}" > </h:commandButton>
    </h:panelGroup>
    <h:panelGroup id="pn_DETAILS_GRP" style="overflow:auto;position:absolute;top:70px;left:400px;width:300px;height:150px;solid black">
    <h:dataTable id="tb_USER_DETAILS" border="1" var="userDtls" value="#{scroll.userTable}" style="width:300px;height:150px">
    <h:column id="SlNo">
    <f:facet name="header">
    <h:outputText value="Sl No" style="font-size:10pt" ></h:outputText>
    </f:facet>
    <h:outputText value="#{userDtls.userSlNo}" style="font-size:8pt"/>
    </h:column>
    <h:column id="firstName">
    <f:facet name="header">
    <h:outputText value="First Name" style="font-size:10pt"/>
    </f:facet>
    <h:outputText value="#{userDtls.userFirst_Name}" style="font-size:8pt"/>
    </h:column>
    <h:column id="lastName">
    <f:facet name="header">
    <h:outputText value="Last Name" style="font-size:10pt"/>
    </f:facet>
    <h:outputText value="#{userDtls.userLast_Name}" style="font-size:8pt"/>
    </h:column>
    </h:dataTable>
    </h:panelGroup>
    </h:form>
    </body>
    </html>
    </f:view>
    ----------------------------------------------------------------------------------------------------------------------------
    2) Create a package subin and inside subin package create javaclass file DataTable.java
    DataTable.java
    /*
    * To change this template, choose Tools
    Templates
    * and open the template in the editor.
    */
    package subin;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    /**
    *
    * @author SubinSuresh
    */
    public class DataTable {

    private HashMap userDtlsMap = new HashMap();
    private List userTable = new ArrayList();

    public void bt_SAVEActionPerformed() {
    System.out.println("Debug bt_SAVEActionPerformed");
    for (int i = 0; i < 15; i++) {
    userDtlsMap = new HashMap();
    System.out.println("Debug i"+i);
    userDtlsMap.put("userSlNo", "" + (i + 1));
    userDtlsMap.put("userFirst_Name", "subin");
    userDtlsMap.put("userLast_Name", "suresh");
    userTable.add(userDtlsMap);
    }
    }

    /**
    * @return the userDtlsMap
    */
    public HashMap getUserDtlsMap() {
    return userDtlsMap;
    }

    /**
    * @param userDtlsMap the userDtlsMap to set
    */
    public void setUserDtlsMap(HashMap userDtlsMap) {
    this.userDtlsMap = userDtlsMap;
    }
    /**
    * @return the userTable
    */

    public List getUserTable() {
    return userTable;
    }

    /**
    * @param userTable the userTable to set
    */

    public void setUserTable(List userTable) {
    this.userTable = userTable;
    }
    }

    -------------------------------------------------------------------------------------------------------------------
    3)Mapping in faces-config.xml file
    <managed-bean>
    <managed-bean-name>scroll</managed-bean-name>
    <managed-bean-class>subin.DataTable</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>



    JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

    Saturday, September 18, 2010

    AlphaNumeric Validator in JSF

    Few days back i discussed Javascript function to restrict special characters,
    Today we will see serverside alphanumeric validator for Jsf.
    This serverside validator is used to validate and restrict special character entering into database.

    Steps for creating AlphaNumeric Validator
    1) Create AlphaNumeric.jsp file
    AlphaNumeric.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
    <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
    <%@taglib prefix="jc" uri="http://jsf-components" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <%--
    This file is an entry point for JavaServer Faces application.
    --%>
    <f:view>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>JSP Page</title>
    </head>
    <body>
    <h:form >
    <jc:AlertMessage />
    <h:panelGroup>
    <h:outputText id="lb_No"value="Label.:" />
    <h:inputText id="tf_NO" autocomplete="off" binding="#{alphanumeric.tf_NO}" >
    <f:validateLength maximum="6" minimum="1"/>
    <f:validator validatorId="alphaNumeric"/>
    </h:inputText>
    <h:commandButton id="cb_save" value="Save" action="#{alphanumeric.bt_SAVEActionPerformed}" > </h:commandButton>
    </h:panelGroup>
    </h:form>
    </body>
    </html>
    </f:view>
    ------------------------------------------------------------------------------------------------------------------------------
    2) Create a package subin and inside subin package create two javaclass files (AlphaNumeric.java and AlphaNumericValidator.java)
    AlphaNumeric.java
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package subin;
    import javax.faces.component.html.HtmlInputText;
    /**
    *
    * @author SubinSuresh
    */
    public class AlphaNumeric {

    public void bt_SAVEActionPerformed() {
    System.out.println("Debug bt_SAVEActionPerformed");
    }
    private HtmlInputText tf_NO =new HtmlInputText();

    /**
    * @return the tf_NO
    */
    public HtmlInputText getTf_NO() {
    return tf_NO;
    }

    /**
    * @param tf_NO the tf_NO to set
    */
    public void setTf_NO(HtmlInputText tf_NO) {
    this.tf_NO = tf_NO;
    }
    }
    --------------------------------------------------------------------------------------------------------------------------
    AlphaNumericValidator.java

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package subin;
    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.component.html.HtmlInputText;
    import javax.faces.component.html.HtmlInputTextarea;
    import javax.faces.component.html.HtmlSelectOneMenu;
    import javax.faces.context.FacesContext;
    import javax.faces.validator.Validator;
    import javax.faces.validator.ValidatorException;

    /**
    *
    * @author subin
    */
    public class AlphaNumericValidator implements Validator {

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    String compValue = null;
    boolean flag = false;
    if (component != null && component instanceof HtmlInputText) {
    compValue = (String) ((HtmlInputText) component).getSubmittedValue();
    } else if (component != null && component instanceof HtmlInputTextarea) {
    compValue = (String) ((HtmlInputTextarea) component).getSubmittedValue();
    }
    if (compValue != null && !compValue.equalsIgnoreCase("")) {
    flag = compValue.matches("[a-zA-Z0-9]*");
    }
    if (!flag) {
    if (component instanceof HtmlInputText) {
    ((HtmlInputText) component).setTitle("No special symbols are allowed here");
    } else if (component instanceof HtmlInputTextarea) {
    ((HtmlInputTextarea) component).setTitle("No special symbols are allowed here");
    } else if (component instanceof HtmlSelectOneMenu) {
    ((HtmlSelectOneMenu) component).setTitle("Page got some un-conditional Data");
    }
    throw new ValidatorException(new FacesMessage("No special symbols are allowed"));
    }
    }
    }
    -------------------------------------------------------------------------------------------------------------------------
    3)Mapping in faces-config.xml file

    <managed-bean>
    <managed-bean-name>alphanumeric</managed-bean-name>
    <managed-bean-class>subin.AlphaNumeric</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <validator>
    <validator-id>alphaNumeric</validator-id>
    <validator-class>subin.AlphaNumericValidator</validator-class>
    </validator>

    When we enter some specialcharacter in textbox and click on save button it shows a popup alert No special symbols are allowed.
    Note:This validation occur before entering action method of save button i.e why "Debug bt_SAVEActionPerformed" is not printed in the output console.


    JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

    Thursday, September 16, 2010

    Reading Postgres Database Connection from properties file using ResourceBundle class

    DB.java

    import java.sql.*;
    import java.util.*;

    public class DB
    {
    static ResourceBundle rb = ResourceBundle.getBundle("myapp", Locale.getDefault());

    public static Connection getConnection ()
    {
    Connection conn = null;

    try {
    Class.forName (rb.getString("dbDriver"));
    conn = DriverManager.getConnection(rb.getString("dbURL"), rb.getString("Username"), rb.getString("Password"));
    } catch (Exception e) {
    e.printStackTrace();
    }
    return conn;
    }


    public static void closeConnection (Connection conn)
    {

    try {
    if (conn !=null)
    {
    conn.close();
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    --------------------------------------------------------------------------------

    CallDB.java

    import java.sql.*;
    import java.util.*;


    public class CallDB
    {
    static ResourceBundle rb = ResourceBundle.getBundle("sql", Locale.getDefault());

    public static void loadAndShowResultSet()
    {
    Connection conn = null;
    Statement stmt = null;

    try {
    conn = DB.getConnection ();
    stmt = conn.createStatement();

    ResultSet rset = stmt.executeQuery(rb.getString("sql.query"));
    while (rset.next())
    {
    System.out.println (rset.getString(1));
    }

    }
    catch (Exception e) {
    e.printStackTrace();
    }
    finally
    {
    try {
    stmt.close();
    DB.closeConnection (conn);
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    public static void main(String args[])
    {
    try {
    CallDB callDB= new CallDB();
    callDB.loadAndShowResultSet();
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

    ------------------------------------------------------
    myapp.properties

    dbDriver=org.postgresql.Driver
    dbURL=jdbc:postgresql://localhost:5432/dbname
    Username=postgres
    Password=postgres

    --------------------------------------------------------

    sql.properties

    sql.query=select first_name from username;

    JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

    Wednesday, September 15, 2010

    Contact Me

    Contact :
    E-Mail: subicoolkerala@gmail.com
    WebSite:www.subinsuresh.blogspot.com

    Creating show dektop icon in windows

    Steps for creating show desktop icon in windows platform

    1.Open a text file

    2.Write the following code in that file

    [Shell]
    Command=2
    IconFile=explorer.exe,3
    [Taskbar]
    Command=ToggleDesktop

    3.Save the file with 'show dektop.scf'

    By this show desktop icon will create on your desktop

    4.Drag the show desktop icon and drop in quicklaunch

    Now you can minimize all the maximized windows in one shot

    Tuesday, September 14, 2010

    Creating a shortcut key for Folder or File in windows

    If you are using a file or folder very frequently create a shortcut key 
    Suppose you have a folder called "Softwares" in D drive
    If you want to create shortcut for this folder

    Right click on folder select Send To-->Desktop(create shortcut) option from context menu
    By this you can see shortcut folder for Softwares folder on your desktop
    Now right click on Softwares shortcut folder which is on your desktop
    Select properties option from context menu, you can see properties window
    Now put the cursor in Shortcut Key box and click "Shift" button in keyboard
    You can see Crtl+Alt+ in the box
    You can give shortcut key as you want for ex: Ctrl+Alt+1
    Click Ok button

    So from next time onwards if you enter Ctrl+Alt+1 Softwares folder will be opened.

    Monday, September 13, 2010

    Finding Language

    LangId is a free web service that allows you to identify in which language was text written.
    click here   www.http://langid.net

    Sunday, September 12, 2010

    Windows Task Manager

    In windows we can see Task Manager by using Ctrl+Alt+Del key

    The alternative for this is Ctrl+Shift+Esc key to open Task Manager

    It opens Windows Task Manager window

    In Applications tab by selecting any of application and clicking on End Task you can stop the application

    In Process tab by selecting any of process and clicking on End Process button you can stop the process

    Thursday, September 9, 2010

    Configuring Java environment in Linux

    After installing Java Development Kit(JDK) or Java Runtime Environment(JRE) on Linux, you have to configure java for running or compiling java programs.
    JDK is usually installed into /usr/java directory
    now open the terminal
    now open the bashrc file which is present in /etc directory by using 
    command vi bashrc 
    [subin@wipro-049cafd91 jet7.0-pro]$ cd ..
    [subin@wipro-049cafd91 ~]$ pwd
    /home/subin[subin@wipro-049cafd91 ~]$ cd /
    [subin@wipro-049cafd91 /]$ pwd
    /
    [subin@wipro-049cafd91 /]$ cd /etc
    [subin@wipro-049cafd91 etc]$ pwd
    /etc
    [subin@wipro-049cafd91 etc]$ vi bashrc

    To edit the bashrc file to configure java, press "Insert" button in keyboard

    export JAVA_HOME=/usr/java/jdk1.6.0_14
    export PATH=$JAVA_HOME/bin:$ANT_HOME/bin:$PATH
    export CLASSPATH=/usr/java/jdk1.6.0_14/lib/tools.jar: \ /usr/java/jdk1.6.0_14/lib/dt.jar

    Once you have edited your .bashrc file
    press "escape" button in keyboard
    and type ":wq!" and press enter
    you can see

    [subin@wipro-049cafd91 etc]$ 

    Execute the following command to make the bash shell to re-read the contents of the .bashrc file 
    [subin@wipro-049cafd91 etc]$ source ~/.bashrc

    Now you can compile and execute Java programs in Linux.

    Saturday, September 4, 2010

    Navigation Rule in JSF

    The JavaServer Faces (JSF) Navigation Framework provides navigation rules that allow you to define navigation from view to view (mostly JSP pages) in a Web application. These navigation rules are defined in JSF configuration files along with other definitions for a JSF application. Usually, this file is named faces-config.xml. 
    Here we will see  Navigation Rule Example in JSF
    First create two jsp's login.jsp and home.jsp
    In login.jsp type the below code
    <h:outputLabel id="lb_USR_NAME" value="UserName:" styleClass="label"/>
    <h:inputText  id="tf_USR_NAME"  autocomplete="off"  value="#{userlogin.tf_USR_NAME}"   />
     <h:outputLabel id="lb_PASS" value="Password:" styleClass="label"/>
     <h:inputText  id="tf_PASS" autocomplete="off" value="#{userlogin.tf_PASS}" />
    <h:commandButton id="cb_login" value="Login" action="#{userlogin.submit}"/>
    In home.jsp
     <body>
             <h1>Welcome to homepage </h1>
        </body>
    In login.java paste the below code login.java is inside main package
    package client.gui.main;


    /**
     *
     * @author Subin Suresh
     */
    public class Login{

      public String submit(){
     String status = null;
    String userName = (String) getTf_USR_NAME().toString();
            String passWord = (String) getTf_PASS().toString();
     if (((userName.equals("subin"))) && ((passWord.equals("subin")))) {
    status = "sucess";
    }else{
    status = "failure";
    }

    }

    }
    In faces-config.xml paste below code  

    <managed-bean>
            <managed-bean-name>userlogin</managed-bean-name>
            <managed-bean-class>client.gui.main.Login</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>

     <!-- ========== Navigation Rules Start  ========== -->
        <navigation-rule>
            <description>Navigation Rule for Login page</description>
            <from-view-id>/login.jsp</from-view-id>
            <navigation-case>
                <description>Redirects the page on "SUCCESS" outcome from login.bt_LOGINActionPerformed()</description>
                <from-action>#{userlogin.submit}</from-action>
                <from-outcome>sucess</from-outcome>
                <to-view-id>/home.jsp</to-view-id>
            </navigation-case>
            <navigation-case>
                <description>Redirects the page on "Failure" outcome from login.bt_LOGINActionPerformed()</description>
                <from-action>#{userlogin.submit}</from-action>
                <from-outcome>failure</from-outcome>
                <to-view-id>/login.jsp</to-view-id>
            </navigation-case>
        </navigation-rule>
      <!-- =========== Navigation Rules Ends ========== -->



    JSF Related topics: JCaptcha in JSF, Integrating Richfaces with JSF,Getting client and server sessionId in JSF and more.....

    Watch TV In Google Chrome Browser


    Google Chrome provides too much facilities to users through extensions. There is an extension known as TV Chrome that lets you watch hundreds of channels in Google Chrome browser.
    To watch TV in your browser, Download TV Chrome extension in your browser.


    Click Install Button



    After installation, a small TV Chrome icon will appear on the extension bar.
     


    Click on TV Chrome Icon


    Click on any country



    Click on the channel you want to watch. Windows media plugin is required to play the video. A small pop up will appear, playing the channel.