Archive

Author Archive

Spring not able to retrieve Sybase database metadata

August 29th, 2009 2 comments

Recently, when trying to execute a Sybase stored procedure using SimpleJdbcCall, I found that the Spring framework could not read the database metadata. SimpleJdbcCall uses the metadata to intelligently figure out the parameters and their types and just makes stored procedure invocation painless.

After going through Spring’s source code, I found that Spring uses the database product name to determine how the metadata should be loaded. Turns out that the commonDatabaseName method in the JdbcUtils that is used to get the product name does a string comparison against “sql server” and our Sybase server is named “SQL Server”.

I submitted a patch to do this comparison with out taking considering the case. Hopefully this gets considered in the 3.0 release.

Categories: Spring Tags:

Mousefeed Eclipse Plugin

July 30th, 2009 1 comment

Today, I ran into a really cool eclipse plugin called Mousefeed. Once installed, this plugin will popup a reminder with shortcut information every time a button or a menu item is clicked using mouse.

I find this a great way to quickly learn Eclipse shortcuts and becoming productive with the IDE.

Categories: Solutions Log Tags:

Unobtrusive JavaScript using JQuery

March 7th, 2009 No comments

I feel that an important advantage of using JQuery is its ability to separate behavior from structure. Consider the case where you want to trigger a JavaScript method when a link is clicked. A common implementation would be:



Click Me

Even though this mixing of behavior (JavaScript) and structure (HTML) looks straight forward, it can become a maintenance issue in large projects. This is where JQuery shines. Using JQuery, the above code can be rewritten in a cleaner way:



Click Me

Now, consider a slightly trickier case where context specific parameters need to be passed to the JavaScript method:



Click Me 1
Click Me 2
Click Me 3
Click Me 4
Click Me 5

Here is the refactored version using JQuery:



Click Me 1
Click Me 2
Click Me 3
Click Me 4
Click Me 5
Categories: JQuery, Uncategorized Tags:

JQuery – Five useful tips

March 7th, 2009 2 comments
  1. Selectors
    Before an element can be manipulated using JQuery, it needs to be identified. JQuery provides a powerful syntax for selecting a one or more elements. Here are some simple selectors (notice similarity to CSS element selection):

    • Selecting by id: $(‘#yourelementid’)
    • Selecting by class name: $(‘.yourclassname’)
    • Selecting by tag name: $(‘p’) selects all the

      elements in the page

    Other useful selectors:

    • div > a will select all the links present directly inside a div tag
    • tag[attribute=value] will select all the elements of type tag with the given attribute name and value. For example input[type=’text’] will select all the text tags
    • :checkbox, :radio, :file are shortcuts to select checkboxes, radio buttons and file elements.
    • :hidden selects all the elements that are hidden (such as head and base tags). This DOES NOT select all the form hidden fields.
  2. Reading and Modifying attribute values
    Once a element is selected, its value can be read and modified using attr method, Here are examples:

    • $(‘base’).attr(“href”) reads the href attribute of the base tag
    • $(“#formTextId”).attr(“value”, ‘Test Value’);
  3. Document ready handler
    The document ready handler provides a convenient location to place all the document’s initialization code. JQuery executes this handler right after the browser finishes converting HTML into DOM tree. Here is the syntax for handler:

    $(document).ready(function() {
       // Your code
    });
    

    A shortcut syntax for this:

     $(function() {
          // Your code
     });
    

    It is possible to chain the several handlers and JQuery will execute them in the order in which they are declared.

  4. live() method
    JQuery’s live() method binds a handler to an event for current and future matched elements. This is extremely useful when elements are loaded dynamically (using AJAX for example) and need to have their behavior controlled by JQuery. For example the following code will display a “Print” window when a link of class printLink is clicked.

     $(".printLink").live("click", function(){
    	window.print();
    	return false;	
    });
    

    A JQuery plugin called Live Query provides a similar but more robust functionality

  5. load() method
    Provides a simple and convenient way to inject html content into an element (or set of elements) using Ajax. For example the following code injects html code of a

    element with id ‘paragraphId’ inside test.html page into div with id ‘someDivId’.
    $(‘#someDivId’).load(‘/test.html #paragraphId’);

Categories: JQuery, Uncategorized Tags:

JQuery – Clearing hidden fields

March 6th, 2009 No comments

JQuery’s form plugin provides several convenient methods for clearing/resetting form element values. However, the clearForm method does not reset hidden fields. Here is a simple implementation for clearing hidden fields:

jQuery.fn.clearHiddenFields = function() {
	return this.each(function(){
		$("input[type='hidden']", this).each(function(){
			this.value = '';
		});
	});		
};

Invoking this method is very straightforward:

$("#yourformid").clearHiddenFields();

or simply:

$("form").clearHiddenFields();
Categories: JQuery, Uncategorized Tags:

Spring Ehcache Integration

February 26th, 2009 20 comments

In this post I will share how to cache method results using Ehcache and Spring AOP. This is based on the post

The first step is to add all the required jars to the project. At minimum, the following jars should be present:

Spring and related jars (using 2.5.6 version here):

  • spring-2.5.6.jar
  • commons-logging.jar
  • commons-collections.jar
  • aspectjrt.jar
  • aspectjweaver.jar
  • jsr250-api-1.0.jar

Ehcache and its dependencies (using version 1.5.0):

  • ehcache-1.5.0.jar
  • backport-util-concurrent-3.0.jar
  • jsr107cache-1.0.jar

For the sake of this post, I will be using a DemoService with a method whose results need to be cached.

package com.inflinx.blog.service;
import java.util.List;
public interface DemoService
{
	public List getCarTypes(String filter);
}

Here is a dummy implementation of the above service:

package com.inflinx.blog.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

@Service("demoService")
public class DemoServiceImpl implements DemoService
{

	public List getCarTypes(String filter)
	{
		List carTypes = new ArrayList();
		carTypes.add("Mini");
		carTypes.add("Economy");
		carTypes.add("Sport Utility");
		carTypes.add("Convertible");
		carTypes.add("Standard");
		
		return carTypes;
	}
}

And the application context with bean scanning turned on:




       
       
	   	       
  

The next step in the process is to add ehcache.xml to the classpath. Details on this configuration file can be found at Ehcache web site



	
     
	
	

    

Spring makes integration with Ehcache easy with EhCacheManagerFactoryBean and EhCacheFactoryBean classes. The EhCacheManagerFactoryBean provides access to Ehcache’s CacheManager and the EhCacheFactoryBean exposes caches defined in ehcache.xml.

To make use of these beans, lets add the following to the application context file:




The next step is to create an AOP Aspect that would provide caching transparently:

package com.inflinx.blog.aspect;

import javax.annotation.Resource;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component("cacheAspect")
@Aspect
@Order(2)
public class CacheAspect
{
	@Resource(name="carTypesCache")
	private Cache cache;
	
	@Around("execution(* com.inflinx.blog.service.DemoService.getCarTypes(java.lang.String))")
	public Object cacheCarTypes(ProceedingJoinPoint joinPoint) throws Throwable
	{
		Object[] arguments = joinPoint.getArgs();
		String location = (String)arguments[0];
		Element element = cache.get(location);
		if(null == element)
		{
			Object result = joinPoint.proceed();
			if(null != result)
			{
				element = new Element(location, result);
				cache.put(element);
			}
		}
		return element != null ? element.getValue() : null;
	}
}

Finally, declare the newly created aspect in the application context file:




Spring Modules provides a great alternative for declarative caching with @Cacheable annotation. As of this post, Spring Modules is still in “draft” status.

You can download the source code used in this post here

Categories: Spring Tags: ,

Integrating Quartz with Spring

September 24th, 2008 10 comments

Spring’s reference documentation goes over in detail on integrating Quartz with Spring. However, the technique requires extending Spring’s QuartzJobBean class. Here are steps for achieving the same integration with out dependencies on QuartzJobBean class:

Step 1: Create the Quartz job that needs to be scheduled. Here is a simple Hello world job class:

public class HelloWorldJob implements Job
{
  public void execute(JobExecutionContext jobExecutionContextthrows JobExecutionException
  {
    System.out.println("Hello World");
  }
}
Notice that we are simply implementing org.quartz.Job interface.

Step 2: In the Spring’s context file, define a JobDetail bean for this job. A JobDetail contains metadata for the job such as the group a job would belong to etc.

<?xml version=”1.0″ encoding=”UTF-8″?>
 <beans xmlns=”http://www.springframework.org/schema/beans” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance
   xmlns:p=”http://www.springframework.org/schema/p” xmlns:context=”http://www.springframework.org/schema/context
   xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd“>
 
 <bean id=”helloWorldJobDetail” class=”org.quartz.JobDetail”>
      <property name=”name” value=”helloWorldJobDetail” />
      <property name=”jobClass” value=”local.quartz.job.HelloWorldJob” />
 </bean>

Step 3: Again, in the context file, define a Trigger that would trigger the job execution. For simplicity sake, lets use a SimpleTrigger. More about triggers can be found in the Quartz documentation:

 <bean id=”simpleTrigger” class=”org.quartz.SimpleTrigger”>
     <property name=”name” value=”simpleTrigger” />
     <property name=”jobName” value=”helloWorldJobDetail” />
     <property name=”startTime”>
       <bean class=”java.util.Date” />   
     </property>
  </bean>

The startTime property is set to “now” which means that the job will run as soon as the spring completes bean loading.

Step 4: Finally, define a SchedulerFactoryBean that sets up the Quartz scheduler:

<bean class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>
     <property name=”jobDetails”>
        <list> <ref bean=”helloWorldJobDetail” /> </list>
     </property>
     <property name=”triggers”>
        <list> <ref bean=”simpleTrigger” /> </list>
     </property>
 </bean>

Notice that this is the only Spring class used in the configuration. When the application loads the Spring context, the job should run and print “Hello World”

In most cases, the job instances rely on external services to perform their job (such as an email service to send out email). These external components can be easily made available to the job instances via dependency injection. Let’s modify the above class to display a custom message:

 public class HelloWorldJob implements Job
{
  private String message;
  
  public void setMessage(String message)
  {
    this.message = message;
  }
  
  public void execute(JobExecutionContext jobExecutionContextthrows JobExecutionException
  {
    System.out.println(message);
  }
}

Next, in the Spring context file, add a bean that contains the custom message we want to display:

<bean id=”message” class=”java.lang.String”>
  <constructor-arg value=”Hello Again!!” />
 </bean>

With Quartz 1.5 and above, dependency Injection into Quartz jobs can be done via a JobFactory instance. Here are the modifications that need to be done to the Spring context:

<bean id=”jobFactory” class=”org.springframework.scheduling.quartz.SpringBeanJobFactory” />
 
 <bean class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>
      <property name=”jobFactory” ref=”jobFactory” />
      <property name=”schedulerContextAsMap”>
          <map> <entry key=”message” value-ref=”message” /> </map>   
      </property>
      <property name=”jobDetails”>
         <list> <ref bean=”helloWorldJobDetail” /> </list>
      </property>
      <property name=”triggers”>
        <list> <ref bean=”simpleTrigger” /> </list>
       </property>
  </bean>

Now when the Spring context gets loaded, the job should run and print “Hello Again!!”.

Categories: Quartz, Spring Tags: ,