Do check out my new blog at http://blog.inflinx.com
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 jobExecutionContext) throws 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 jobExecutionContext) throws 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!!”.
Posted in Quartz, Spring | Tagged Quartz, Spring | Leave a Comment »
Here is some code I came across today:
public class SingletonWannabe
{
private static String SERVER_URL;
private static int port;
private static String protocol;
public SingletonWannabe(String url, int port, String protocol) {
this.SERVER_URL = url;
this.port = port;
this.protocol = protocol;
}
public static String getServerUrl() {
return SERVER_URL;
}
public static int getPort() {
return port;
}
public static String getProtocol() {
return protocol;
}
}
This was being used as a singleton in an application
Posted in Bad Code | Leave a Comment »
In this post I will highlight some of Lucene’s search functionality. Refer to part one of this series for creating indexes using Lucene.
Searching in Lucene involves submitting a search query to the IndexSearcher class. The IndexSearcher executes this query against an index and returns search results (hits). Here is a prototype implementation:
public Hits searchIndex(Query q) throws Exception
{
IndexSearcher searcher = new IndexSearcher("c:/lucene/index");
return searcher.search(q);
}
The IndexSearcher constructor takes the path to the index it needs to search against. The IndexSearcher class is thread safe and Lucene API recommends opening and using one IndexSearcher for all searches.
The Query class is an abstract class that encapsulates a user input. The simplest way to generate a concrete query is to use the QueryParser class. The following code generates a query for all the employees whose first name is Judy:
QueryParser parser = new QueryParser("firstName", new SimpleAnalyzer());
Query query = parser.parse("Judy");
Hits hits = searchIndex(query);
The first parameter to the QueryParser is the field name in the document against which the query is being made. For better results, the analyzer passed as the second parameter should be of the same type that is used while creating indexes.
The Hits class encapsulates search results. Hits can be easily iterated over to get to the “interesting” stuff:
for(int i = 0; i < hits.length(); i++)
{
Document d = hits.doc(i);
System.out.println(d.getField("firstName").stringValue());
}
QueryParser does a good job at interpreting user entered search expressions. If developers find limitations using QueryParser, Lucene provides a nice API to programmatically generate and combine queries. Let’s say a user wants to find all the Employees with first name Judy and last name Test:
Query fnQuery = new TermQuery(new Term("firstName", "Judy"));
Query lnQuery = new TermQuery(new Term("lastName", "Test"));
BooleanQuery query = new BooleanQuery();
query.add(fnQuery, BooleanClause.Occur.MUST);
query.add(lnQuery, BooleanClause.Occur.MUST);
// Notice we are not analyzing user entered input before executing search
Hits hits = searchIndex(query);
By default the returned search results are ordered by decreasing relevance. This however can be easily changed using overloaded search methods in IndexSearcher. The following code sorts the results of the above query on first name field:
Sort sort = new Sort("firstName");
Hits sortedHits = indexSearcher.search(query, sort);
An important thing to remember is that fields used for sorting must not be tokenized. Otherwise you will run into this exception: “there are more terms than documents in field “XXXXXX”, but it’s impossible to sort on tokenized fields”.
Posted in Getting Started | Tagged Lucene, Search | Leave a Comment »