Wednesday, November 24, 2010

Spring JDBC/DAO Example

Program to retrieve customer details using Spring JDBC  
Database details :  
·         Driver ="com.mysql.jdbc.Driver“            
·         url="jdbc:mysql://localhost:3306/mydatabase“    
·         Username ="root”
·         Password ="password”

Step 1 : Create a table in the database and insert some values
create table customer (
  id varchar(36) not null,
  name varchar(32) not null 
);
insert into customer (id, name) values ('vels','Java vel);
insert into customer (id, name) values ('jjohn','Java John');


Step 2:  Configure the DataSource information into the SpringContext.xml
          This datasource details will be used in Spring JDBC/DAO class
          ....
<bean id="dataSource” class="org.springframework.jdbc.datasource.DriverManagerDataSource">        
                <property name="driverClassName" value="com.mysql.jdbc.Driver" />               
                <property name="url” value="jdbc:mysql://localhost:3306/mydatabase" />      
                <property name="username" value="root" />
                <property name="password" value="password" />
</bean>
                <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >         
                                <property name="dataSource" ref="dataSource" />
                </bean>

Step 3:  Create a Data Model  for “Customer”
package com.vels.spring.jdbc;
public class Customer {
private String id;
private String name;
public Customer() {
super();
}
public Customer(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString(){
    return String.format("%s id= %s, name= %s", getClass().getSimpleName(), this.id, this.name);
}
}

Step 4:  Create a Spring DAO Class
package com.vels.spring.jdbc;
public interface CustomerDAO {
public List<Customer> getCustomers();
}
Step 4: Create Spring DAO Impl class CustomerDAOImpl
package com.vels.spring.jdbc;
public class CustomerDAOImpl implements CustomerDAO{
                 private final JdbcTemplate jdbc;
public CustomerDAOImpl(JdbcTemplate jdbc) {
super();
this.jdbc = jdbc;
}
          }
Step 5:   Add the implementation to the getCusomters() method in the SpringDAO Impl class
          public List<Customer> getCustomers() {
                       List<Customer> result= (List<Customer>) jdbc.query("select id, name from customer”,  
                       new ResultSetExtractorImpl());
                return result;
         }
Step 6: Create a inner class ResultSetExtractorIml into the  CustomerDAOImpl.java :
private class ResultSetExtractorImpl implements ResultSetExtractor{
                                public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                                                List<Customer> list = new ArrayList<Customer>();
                                                while(resultSet.next()){
                                                                Customer customer = new Customer(
                                                                                                resultSet.getString("id"),
                                                                                                resultSet.getString("name"));
                                                                list.add(customer);
                                                }
                                                return list;
                                }
                               
                }

Step 7: add the Spring DAO Details into the SpringContext.xml file
<bean name="customerDAO" class="com.vels.spring.jdbc.CustomerDAOImpl">
                <constructor-arg ref="jdbcTemplate" />
</bean>


The Final DAOImpl calss look like

package com.vels.spring.jdbc;
public class CustomerDAOImpl implements CustomerDAO{
                 private final JdbcTemplate jdbc;
public CustomerDAOImpl(JdbcTemplate jdbc) {
super();
this.jdbc = jdbc;
}
public List<Customer> getCustomers() {
                List<Customer> result= (List<Customer>) jdbc.query("select id, name from customer”, new ResultSetExtractorImpl());
                return result;
}
private class ResultSetExtractorImpl implements ResultSetExtractor{
                                public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
                                                List<Customer> list = new ArrayList<Customer>();
                                                while(resultSet.next()){
                                                                Customer customer = new Customer(
                                                                                                resultSet.getString("id"),
                                                                                                resultSet.getString("name"));
                                                                list.add(customer);
                                                }
                                                return list;
                                }             
                }
          }
Step 8 : Write a util class to load the beans definition
package com.vels.spring.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUtil {
                public static final ApplicationContext SPRING_CONTEXT = new ClassPathXmlApplicationContext(new String[]{"config/SpringContext.xml"});
}
Step 9: Write a client class CustomerDAOClient
Public class CustomerDAOClient {
                Public static void main(String [] a){
                                CustomerDAO cust = SpringUtil.SPRING_CONTEXT.getBean("customerDAO ");
                                List<Customer> list = cust.getCustomers();
// iterate the list....
}
}

Monday, November 22, 2010

How to Create JSP ToolTips in Javascript

Creating a ToolTips in JSP Using javascript 

  // Display the string value as a tooltip
  // This should be called in onMouseMove() and onMouseOver()

  // Usage onMouseOver('abc'.showTooltip()) onMouseMove('abc'.showTooltip())



  String.prototype.showTooltip =
  function()
  {
   var tooltip = document.createElement("div");
   tooltip.id = "Tooltip_1";
   tooltip.style.position = 'absolute';
   tooltip.style.display = 'block';
   tooltip.style.backgroundColor = '#FFFFE1';
   tooltip.style.color = '#000000';
   tooltip.style.fontFamily = "Verdana, Arial, Helvetica, sans-serif";
   tooltip.style.fontWeight ="normal";
   tooltip.style.fontSize = "11px";
   tooltip.style.border =  '1 #000000 solid';
   x = event.clientX + document.body.scrollLeft;
   y = event.clientY + document.body.scrollTop + 10;
   tooltip.style.left = x;
   tooltip.style.top = y;
   document.body.appendChild(tooltip);
   var prefix = '&nbsp;&nbsp;';
   var suffix = '&nbsp;&nbsp;';
   tooltip.innerHTML = prefix +
   this + suffix;
  };

Javscript ToolTip usage :

To Showthe tooltip text call the showTooltip() function from your jsp/html page :
....
<input type="text" name="fileName" onmouseover="('Tool Tips sample'.showTooltip())" />
</td>
....
<td valign="bottom">

Friday, November 19, 2010

Sorting items in the html select/list box using javascript

How to Sort the items in the list box based on the text

function
sortListBox(box)
{
var
temp_opts = new Array();
var temp = new Object();
for(var i = 0; i < box.options.length; i++)
{
temp_opts[i] = box.options[i];
}
for
(var x = 0; x < temp_opts.length - 1; x++)
{
for
(var y =(x + 1); y < temp_opts.length; y++)
{
if
(temp_opts[x].text > temp_opts[y].text)
{
tempT = temp_opts[x].text;
tempV = temp_opts[x].value;
temp_opts[x].text = temp_opts[y].text;
temp_opts[x].value = temp_opts[y].value;
temp_opts[y].text = tempT;
temp_opts[y].value = tempV;
}
}
}
for
(var i = 0; i < box.options.length; i++)
{
box.options[i].text = temp_opts[i].text;
box.options[i].value = temp_opts[i].value;
}
}

How to check the given date is before/after the specified date using javascript

How to check if  the given date is before/after the specified date using javascript

<script language="javascript">

// Checks if this date is before the specified date
Date.prototype.before =
function(_date)
{
if
(this.getFullYear() > _date.getFullYear())
{
return false
;
}
else if
(this.getFullYear() == _date.getFullYear())
{
if
(this.getMonth() > _date.getMonth())
{
return false
;
}
else if
(this.getMonth() == _date.getMonth())
{
if
(this.getDate() > _date.getDate())
{
return false
;
}
}
}
return true
;
}
;
// Checks if this date is after the specified date
Date.prototype.after =
function(_date)
{
if
(this.getFullYear() < _date.getFullYear())
{
return false
;
}
else if
(this.getFullYear() == _date.getFullYear())
{
if
(this.getMonth() < _date.getMonth())
{
return false
;
}
else if
(this.getMonth() == _date.getMonth())
{
if
(this.getDate() < _date.getDate())
{
return false
;
}
}
}
return true
;
}

</script>

Usage :

.....


date t1 = new Date();
date t2 = new Date(yyyy, mm, dd);

alert(t1.after(t2);

....

How to check a given string is a Valid Alphabet, Valid number and Valid alpha numeric in javascript

 Check a given string a Valid Alphabet, Valid number and Valid alpha numeric in javascript


// Checks whether the string contains only alphabets
_this = String.prototype;
_this.isValidAlphabet =
function()
{
var
charpos = this.search("[^A-Za-z]");
if(this.length > 0 && charpos >= 0)
return false;
return true;
}
;
// Checks whether the string is valid number
_this.isValidNumber =
function()
{
var
charpos = this.search("[^0-9]");
if(this.length > 0 && charpos >= 0)
return false;
return true;
}
;
// Checks whether the string is a valid alpha numeric value
_this.isValidAlphaNumeric =
function()
{
var
charpos = this.search("[^A-Za-z0-9-_ ]");
if(this.length > 0 && charpos >= 0)
return false;
return true;
}

...

Usage  :

var str = document.forms[0].element['name'].value;

alert(str.isValidAlphabat())
....
///

Trim function in javascript

To Trim a string using javascript

<script language="JavaScript" type="text/javascript">
String.prototype.trim =
function()
{
str = this;
// remove leading spaces
while(str.substring(0, 1) == ' ')
{
str = str.substring(1, str.length);
}
// remove trailing spaces
while(str.substring(str.length - 1, str.length) == ' ')
{
str = str.substring(0, str.length - 1);
}
return
str;
}
</script>

Usage  :
...
var s = document.forms[0].elements['t1'].value;
alert(s.trim());
....

Wednesday, November 17, 2010

Logger Example using Spring AOP

Spring AOP logger example
      AOP(Aspect Oriented Programming )
  • Aspect - General feature which we want to apply globally to our application (logging, performance monitoring, exception handling, transaction management, etc).
  • Advice - A chunk of code that is invoked during program execution, and is a piece of the logic for implementing your aspect.
  • Joinpoint - A location in the code where an advice can be executed (such as field access, method invocation , constructor invocation, etc.). Spring's built-in AOP only supports method invocation
  • Pointcut - A pointcut is a set of many joinpoints where an advice should be executed.
  • Targets/Target Objects - The objects you want to apply an aspect or set of aspects to!
Steps Involved in implementing logging using Spring AOP
Step 1 :  Write a Logger class
 package com.vels.spring.aop;

/**
 * @author velmurugan pousel
 * @project Spring AOP
 * created on Nevember 15 2010
 */

public interface Calculator {
      public double add(double a, double b);
      public double subtract(double a, double b);
      public double divide(double numerator, double denominator);
      public double multiply(double a, double b);


}
Step 2 :  Implement the calculator functionality
package com.vels.spring.aop;
 /**
 * @author velmurugan pousel
 * @project springAOP
 * created on Nov 16, 2010
 */

public class CalculatorImpl implements Calculator {

      public double add(double a, double b) {
            return (a+b);
      }

      public double divide(double numerator, double denominator) {
            if(denominator == 0){
                  throw new RuntimeException("Divide by Zero error");
            }
            return (numerator/denominator);
      }

      public double multiply(double a, double b) {
            return (a*b);
      }

      public double subtract(double a, double b) {
            return (a-b);
      }
 
}
Step 3:  Create a SpringContext.xml file(which will have all context information)
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

       <bean id="calculator" class="com.vels.spring.aop.CalculatorImpl" />
      </beans>
Step 4: Write the advice class(a piece of the logic for implementing your aspect)
Method Before Advice : this advice will be called before the method execution
package com.vels.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

 /**
 * @author velmurugan pousel
 * @project springAOP
 * created on Nov 16, 2010
 */


public class CalculatorLoggingBeforeAdvice implements MethodBeforeAdvice {

      public void before(Method method, Object[] args, Object target)
                  throws Throwable {
            System.out.print("Logging Before method access >>");
            System.out.print("Input Values " + method.getName() + ">>");
            for (Object arg : args) {
                  System.out.print(arg + " ");
            }
            System.out.println();

      } 

     }
     Method After Runturnig Advice : this advice will be called after the method execution
package com.vels.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
 /**
 * @author velmurugan pousel
 * @project springAOP
 * created on Nov 16, 2010
 */
public class CalculatorLoggingAfterAdvice implements AfterReturningAdvice{

      public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
            System.out.println("Return value "+method.getName()+">>"+returnValue);       
            System.out.println("Log after return   ");     
      }    

}
Throws Advice : This advice will be called whenever exception thrown
package com.vels.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
 /**
 * @author velmurugan pousel
 * @project springAOP
 * created on Nov 16, 2010
 */
public class CalculatorLoggingThrowsAdvice implements ThrowsAdvice{

      public void afterThrowing(Method method, Object[] args, Object target,Throwable e) throws Throwable {
            System.out.println("Exception "+method.getName()+" "+e.getMessage());
      }


      }
Step 4 : Write the util class to load the context file
package com.vels.spring.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUtil {
      public static final ApplicationContext SPRING_CONTEXT = new ClassPathXmlApplicationContext(new String[]{"config/SpringContext.xml"});
}
Step 4: Configure all the advice in the context file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

       <bean id="calculator" class="com.vels.spring.aop.CalculatorImpl" />
       
       <bean id="loggingBeforeAdvice" class="com.vels.spring.aop.CalculatorLoggingBeforeAdvice" />
       <bean id="loggingAfterAdvice" class="com.vels.spring.aop.CalculatorLoggingAfterAdvice" />
       <bean id="loggingThrowsAdvice" class="com.vels.spring.aop.CalculatorLoggingThrowsAdvice" />
       
     
      <bean id="calculatorProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
           
            <property name="target" ref="calculator" />
             
            <property name="interceptorNames">             
                  <list>                       
                        <value>loggingBeforeAdvice</value>       
                        <value>loggingAfterAdvice</value>
                        <value>loggingThrowsAdvice</value>
                  </list>
            </property> 
      </bean>
           
</beans>

loggingBeforeAdvice advice will be executed before every method invocation on CalculatorImpl calss.
loggingAfterAdvice advice will be executed after every method invocation on CalculatorImpl calss.
loggingThrowsAdvice advice will be executed when an exception got in every method invocation on CalculatorImpl calss.
Step 5: Write a client to test the logging functionality
+package com.vels.spring.aop;

import com.vels.spring.util.SpringUtil;

 /**
 * @author velmurugan pousel
 * @project springAOP
 * created on Nov 16, 2010
 */
public class CalculatorClient {
      public static void main(String[] args) {
           
            Calculator calculator = (Calculator)SpringUtil.SPRING_CONTEXT.getBean("calculatorProxy");
            calculator.subtract(3, 2);
            calculator.multiply(2, 2);
            calculator.divide(2, 0);
             
      } 

}

Output : >>>>>>>>>>
Note : Place the config folder under src folder and include spring.jar and common-logging.jar into the classpath