Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, May 14, 2011

Subtract ndays from given Date

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
   /**
         * @param date
         * @param days
         * @param format
         * @return
         */
        public static String subtractDays(Date date, Integer days,String format) {

              
                String formattedDate = null;
                if(null != date && null != format){
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        calendar.add(Calendar.DATE, -days);
                        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
                        formattedDate=dateFormat.format(calendar.getTime());
                }
                return formattedDate;
        }

Monday, May 9, 2011

Adding ndays to given Date

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

       /**
         * @param date
         * @param days
         * @param format
         * @return

         */
        public static String addDays(Date date, Integer days, String format) {

                String formattedDate = null;
                if(null != date && null != format){
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(date);
                        calendar.add(Calendar.DATE, days);

                        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
                        formattedDate = dateFormat.format(calendar.getTime());
                }
              
                return formattedDate;
        }
      


Saturday, February 26, 2011

What is a Framework?

Framework is special software that is capable of developing applications based on certain architecture having ability to generate certain logics of application development dynamically.

Tuesday, November 2, 2010

Remove Duplicate value from ArrayList

ArrayList arrayListSubin = new ArrayList();
  
 
arrayListSubin.add("A");
 
arrayListSubin.add("A");
 
arrayListSubin.add("B");
 
arrayListSubin.add("B");
 
arrayListSubin.add("B");
 
arrayListSubin.add("C");
  
  //Create a HashSet which allows no duplicates
  HashSet hashSet = new HashSet(
arrayListSubin);

  //Assign the HashSet to a new ArrayList
  ArrayList arrayList2 = new ArrayList(hashSet) ;
  
  //Ensure correct order, since HashSet doesn't
  Collections.sort(arrayList2);
  
  for (Object item : arrayList2)
    System.out.println(item);

Note that you will have to sort the ArrayList if you want to be sure that the items remain
in correct order by calling the sort method of the Collection class.

This will produce the following output:

A
B
C

Thursday, October 28, 2010

Java program to reverse contents in a file

Below contains java program to read the contents of a file,reverse the contents of the file and write it back to the file.

1)create text.txt in D: drive of your system and type the contents say subin suresh
2)Create java class and type the below code
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package reverse;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
*
* @author subin_s
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner scanner = new Scanner(new File("D:/test.txt")).useDelimiter("\\Z");
String contents = scanner.next();
System.out.println("Original String : " + contents);
contents = new StringBuffer(contents).reverse().toString();
System.out.println("Reversed String : " + contents);
FileWriter fstream = new FileWriter("D:/test.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(contents);
out.close();
}
}

3)Output
Original String : subin suresh
Reversed String : hserus nibus

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.....

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.....

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.

Monday, August 23, 2010

ServerSide Email Validator

In my last post i have written Javascript function for email validation. In this i will be discussing about ServerSide Email Validator. For application to be safe it is necessary to have both client and server side validators.
Steps for implementing ServerSide Email Validator
1. In jsp define the email component in the following way
  <h:outputLabel id="lb_MAIL_ID" value="Mail ID:" styleClass="label"/>
<h:inputText id="tf_MAIL_ID" autocomplete="off" value="#{userlogin.tf_MAIL_ID}" />
2. In java class get email component value and apply serverside email validator for it as shown below

/*
* Getting the tf_MAIL_ID component value
*/
String emailId = (String) getTf_MAIL_ID().toString();
 if (emailId == null || !emailId.matches("^[A-z0-9_\\-\\.]+[@][A-z0-9_\\-]+([.][A-z0-9_\\-]+)+[A-z]{2,4}")) {
             System.out.println("Please enter Valid Email-Id");
        }

Instead of  using  System.out.println you can use PopUp AlertMessagebox for JSF  as it clear idea for the user who is using it. 

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

Java program to Get Heap Size of JVM

Java program to Get Heap Size of JVM 

public class GetHeapSize {
        public static void main(String[]args){
    
            //Get the jvm heap size.
            long heapSize = Runtime.getRuntime().totalMemory();
    
            //Print the jvm heap size.
            System.out.println("Heap Size = " + heapSize);
        }
    }

Thursday, August 19, 2010

Increasing Heap size of Java

Java heap is the heap size allocated to JVM applications which takes care of the new objects being created. If the objects being created exceed the heap size, it will throw an error saying memoryOutofBound

Java's default heap size limit is 128MB
. If you need more than this, you should use the -Xms and -Xmx command line arguments when launching your program:

java -Xms -Xmx


Java programs executes in JVM uses Heap of memory to manage the data. If your Java program requires a large amount of memory, it is possible that the virtual machine will begin to throw OutOfMemoryError instances when attempting to instantiate an object. The default heap size if 1 MB and can increase as much as 16 MB.

Setting/Increase JVM heap size

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

Following are few options available to change Heap Size.

1    -Xms        set initial Java heap size
2    -Xmx
       set maximum Java heap size
3    -Xss
        set java thread stack size

For example, you can set minimum heap to 64 MB and maximum heap 256 MB for a Java program HelloWorld.

java -Xms64m -Xmx256m HelloWorld

Getting / Reading default heap size

It is possible to read the default JVM heap size programmatically by using totalMemory() method of Runtime class. Use following code to read JVM heap size.
    public class GetHeapSize {
        public static void main(String[]args){
    
            //Get the jvm heap size.
            long heapSize = Runtime.getRuntime().totalMemory();
    
            //Print the jvm heap size.
            System.out.println("Heap Size = " + heapSize);
        }
    }

Friday, May 21, 2010

Get CurrentDate in YYYY_MM_DD Format

/**
* Here get the current date in format 'YYYY-MM-DD'
*
* @return Current date in format 'YYYY-MM-DD'
*/
public static String getCurrentDate_YYYY_MM_DD() {
// get current date in Format YYYY-MM-DD
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
final String dateFormat = "yyyy-MM-dd";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
System.out.println("debug "+sdf.format(cal.getTime()));
return sdf.format(cal.getTime());
}

convertDateToString

/**
* Convert Date to String
* @param date
* @return
*/
public static String convertDateToString(Date date) {
String rtnString = "";
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
//java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DateUtils.DATE_FORMAT);
if (date != null) {
rtnString = sdf1.format(date);
}
return rtnString;
}

convertStringToDate

/**
* Convert String to Date
* @param dateString
* @return
*/
public static Date convertStringToDate(String dateString) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy");
java.util.Date dt = null;
try {
dt = sdf.parse(dateString);
System.out.println("Debug dt :"+dt);
} catch (java.text.ParseException p) {
System.out.println(p.toString());
}
return dt;
}

convertDatePattern

/**
* Change the Date pattern from yyyy/MM/dd to dd-MM-yyyy
* @param dateToParse
* @return
* @throws java.text.ParseException
*/
public static String convertDatePattern(String dateToParse) throws ParseException {
System.out.println("Debug inside convertDatePattern");
if (dateToParse != null && !dateToParse.equals("")) {
if (dateToParse.contains("-")) {
return dateToParse;
} else {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd");
String dateStringToParse = dateToParse;
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf1.parse(dateStringToParse);
dateToParse = sdf2.format(date);
System.out.println("Debug dateToParse:"+dateToParse);
return dateToParse;
}
} else {
System.out.println("Please check the date");
}
return "";
}

Note:Input to this method should be yyyy/MM/dd format.

Thursday, May 20, 2010

Getting CurrentServerDate

/**
* Wrapper / convenience method for getting the current server date
*
* @return Current server Date - "null" if error occurs
*/
public static Date getCurrentServerDate() {
Date serverDate = null;
serverDate = new java.util.Date();
return serverDate;
}