Tuesday, February 10, 2009

One CVS trick with eclipse

Recently I had a need to commit some local uncommitted change of a branch into another branch. I was little skeptical that I might loose all the local changes and redo them, manually, again in the other branch. Some soul searching in eclipse help document, revealed that I can do such things using "Team -> Switch to another branch or version". It uses sticky tags to move the uncommitted changes into the new version/branch instead of replacing. Once you have "switched" to this new branch, you can commit them gladly. And, it works! But there is one problem. Suppose there is some conflicting file, i.e., you have modified a file "A" locally and someone else also has made some conflicting changes in "A" in this other branch. In this particular situation, eclipse/cvs screws your code gracefully. i.e., without any warning/error. It looses all local changes you made! So my personal opinion is before "switching" to another branch, do a "compare with" that branch. Find out if there is any conflict. In case you find any conflict, back them up somewhere. After "switching" to the other branch manually check which state these files are. You might need them to fix manually.

Monday, December 01, 2008

Quick HOWTO : Quartz with JBoss

While searching for some job scheduler tool, I came across this Open Source tool, called, Quartz. Most importantly my requirement was to be able to use it from inside an application server like JBoss. After reading some tutorials, I gave it a go. Let me just brief my experience here.

Quick Intro
Fundamental entities with Quartz or with any other job schedulers are tasks and triggers invoking them. Quartz has got two kinds of triggers: SimpleTriggers and CronTriggers which are very much similar to Unix Cron triggers. There are two ways one can store the jobs in Quartz. RAMJobStore is the most simple one but the tasks stored here do not get persisted, i.e., jobs get forgotten once the server restarts. Other type of job stores are JDBCJobStore. As the name suggests with these job stores, jobs are stored in relational databases. Quartz supports most of the standard databases like MySQL, Oracle and etc. There are two kinds of JDBCJobStores available: JobStoreTX and JobStoreCMT. JobStoreTX is supposed to be used stand alone whereas JobStoreCMT is meant to be used from an application server. As my requirement was to use it with JBoss I used only JobStoreCMT. And, used it with MySQL as the back end database.

Quartz as a JBoss service
JBoss 4.2.2.GA already has got quartz bundled with it. But actually you can not do much with this as it supports only RAMJobStore. So to use it effectively we need to do some more. We have to copy quartz-1.6.2.jar and quartz-jboss-1.6.2.jar in the JBOSS_HOME/server/server_mode/lib directory. Then, we need to create a xml file to configure Quartz as a service in JBOSS_HOME/server/server_mode/deploy directory.

Create the data base
We need to create the database where all job and trigger information will get stored eventually. The sql scripts are bundled with Quartz download under docs/dbTables directory.

quartz-service.xml
As already mentioned we need to create the quartz-service file . Let me just enclose a sample file.

<server>

<mbean code="org.quartz.ee.jmx.jboss.QuartzService" name="user:service=QuartzService,name=QuartzService">
<!-- JNDI name for locating Scheduler, "Quartz" is default. -->

<attribute name="JndiName">Quartz</attribute>
<attribute name="Properties">
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#

# org.quartz.scheduler.classLoadHelper.class =

org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false
org.quartz.scheduler.xaTransacted = false

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
org.quartz.threadPool.threadPriority = 4

org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreCMT
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.dataSource = QUARTZ
org.quartz.jobStore.nonManagedTXDataSource = QUARTZ_NO_TX
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.dataSource.QUARTZ.jndiURL = java:QuartzDS
org.quartz.dataSource.QUARTZ_NO_TX.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.QUARTZ_NO_TX.URL = jdbc:mysql://localhost:3306/Quartz
org.quartz.dataSource.QUARTZ_NO_TX.user = root
#org.quartz.jobStore.maxMisfiresToHandleAtATime=0

</attribute>

</mbean>
</server>
The point to note here is that we'll need two datasource elements for this configuration. One is standard datasource managed by JBoss container (see the line org.quartz.jobStore.dataSource = QUARTZ) another one is not managed by the container, on which quiatz can call commit/rollback by itself. We have to confugure the container managed datasource as a standard jboss *-ds file, whereas we configure the non_managed_datasource inside this quartz-service.xml itself. Here one gotcha is for the container_managed datasource, we'll need to use XA datasource (I am not very sure why regular local datasource does not work. Maybe reason being Quartz works in a clustered environment, just a guess though). Let me just attach a sample mysqlquartz-ds file here:

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<xa-datasource>
<jndi-name>QuartzDS</jndi-name>

<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
<xa-datasource-property name="URL">jdbc:mysql://localhost:3306/Quartz</xa-datasource-property>
<user-name>root</user-name>
<password></password>
<transaction-isolation>TRANSACTION_READ_COMMITTED</transaction-isolation>
<max-pool-size>5</max-pool-size>
<min-pool-size>0</min-pool-size>

<blocking-timeout-millis>2000</blocking-timeout-millis>
<idle-timeout-minutes>2</idle-timeout-minutes>
<track-connection-by-tx>true</track-connection-by-tx>
<no-tx-separate-pools>false</no-tx-separate-pools>


<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<!-- <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name> -->
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</xa-datasource>

</datasources>
Creating a job
Once you get the configuration right, other things are pretty simple.

InitialContext ctx = new InitialContext();
Scheduler scheduler = (Scheduler) ctx.lookup("Quartz");
Trigger trigger = TriggerUtils.makeDailyTrigger("myTrigger", 0, 0); //a trigger which gets fired on each midnight
trigger.setStartTime(new Date());

JobDetail job = new JobDetail("jobName", "jobGroup", Executor.class);

job.getJobDataMap().put("Name", "Abdul Sahid Khan");
job.getJobDataMap().put("Age", 125);

scheduler.scheduleJob(job, trigger);
So you get a handle to the Scheduler object using jndi lookup. Remember we set the jndi name in quartz-service.xml file. Then we create a trigger. There is various ways to create a trigger. TriggerUtils is a utils class provided by Quartz itself which gives mane factory methods to create simple triggers. Then we need to create a job. There is no Job class (well, there is an interface by that name but let us now pretend that it does not exist), instead we will create a JobDetail object. While creating JobDetail object we need to provide an Executor class which will be used when this particular job gets fired by the Scheduler. We can store job specific information in the datamap provided by JobDetail object. These information can be used in the Executor class.

Execute the job
The job gets executed by the class which was passed while creating the JobDetail object. This Executor class needs to implement earlier_ignored Job interface. And that mandates Executor to have a method called execute().

public class Executor implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
String jobName = context.getJobDetail().getName();
String groupName = context.getJobDetail().getGroup();
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String name = (String) dataMap.get("Name");
Integer age = (Integer) dataMap.get("Age");
logger.info("Job received name: " + jobName + " , Group: " + groupName);
logger.info("Name: " + name + " , Age: " + age);
}
}
Delete the job
To delete a job we need to know the name and group of the job.

InitialContext ctx = new InitialContext();
Scheduler scheduler = (Scheduler) ctx.lookup("Quartz");
scheduler.deleteJob("jobName", "jobGroup");
Here one must remember that you can not delete a job from inside the execute method, that will create a lock which will cause JVM to crash. So delete should be handled as different process like create.

One last thing about Jboss
Sometime, business logic needs you to have your Executor class inside the your EAR/WAR application. Now that will create a dependency problem while starting the jboss server. Each time Quartz service starts, it tries to recover if there is any misfired jobs. But if Quartz starts before EAR/WAR deploys then we have ClassNotFound problem. To solve this we can use the deploy.last hack given by JBoss. You can create deploy.last directory and put the quartz-service.xml file inside that. That will ensure Quartz service will start after all the application gets deployed.

Reference:
Quartz wiki

Sunday, November 30, 2008

United we stand, do we really?

Wednesday I came back late after attending one of my friends marriage party. I switched on the TV for couple of minutes before going to bed perhaps only to discover that there had been another terrorist attack in Mumbai. Since then I feel extremely disturbed and helpless. And, being a Muslim myself, I live in this peculiar mental state of multi-directional feeling of insecurity.

Tonight I was watching this program at NDTV by Burkha Dutt "We the People". And what I saw, pretty much summed up the conflicting, ever_contrasting mood of the whole nation. In one point one of the guest, Simi Garewal, told something like: If you see the flags from all the slums surrounding the Oberoi and other multi-storied building, you'll notice these are neither Indian National Flag, nor they are any party flag like Congress's or BJPs. Perhaps she tried to mean these are flags of our *neighbouring country*. Anyhow, there was this sudden and furious response from one of the young audience: "Pakistan is not the problem, Islam is not the problem, people like Simi are the main problem..." I was absolutely stunned to see this live. I don't know if the person was a muslim himself. The significance of this show is, it shows very clearly how much united we Indians are!

Sunday, September 28, 2008

Trek towards Sandakphu


It has been more than a month I came back from my first ever trekking experience. Last month me and my brother teamed up with 4 of my friends for this trip. Being first ever trek for most of us, we were really excited for this. Perhaps being overenthusiastic, I purchased one 65L rucksack also from UBAC and a pretty good hiking boot from Woodlands. But at the end, I think everything paid off.

We started walking from Manebhanjan on 15th August afternoon. We took a local boy 'Buddha' with us as our guide. The very first thing he told us that he was Buddha, not Buddhadeb the WB CM. Not sure if he was trying to make any political statement! Anyways, we started after covering ourselves with a plastic, as it was raining continuously. But boy! First two kms appeared to be real difficult for novices like us, particularly for me. Perhaps I should have rechecked if I could carry so heavy a backpack. Buddha came to remedy, he carried the backpack for me. We reached Chitrey in the evening and decided to stay the night there. A hotel called Hawk's Nest is available there. We kept some of ours luggage there and started trekking towards Tumbling next day morning around 8 am. We reached Tumbling at 12.30. We stayed the night at Siddartha Lodge. As Singalila National Park was closed due to the monsoon season, we decided not to proceed any further. We also had some time constraint. But next day was like a dream. I got awaken as Soumen jumped from the room, shouting sun has come out. We all came out and saw the majestic Kanchenjunga slowly revealing all its beauty. Clouds disappeared one after another. Sun brought the white icy cover to light, with all its glittering sunlight. Local people say Kanchenjunga family of hills are nothing but Lord Buddha sleeping gracefully. Close look makes the story clear. Kanchenjunga does look like a man sleeping in the eternity. After taking lunch we started trekking again. This was very short. We reached Tonglu in almost 2 hours. It started raining again. We stayed another night at the Trekkers Hut in Tonglu. Buddha went downhill to get some chicken for us. This was another good thing about our trip: we never compromised about our food! Next day, we started in the morning and reached Chitrey around 12'o clock. We took our lunch there and started the return journey. With help of Buddha we contacted a person at Manebhanjan, who is popularly called as "Masterjee". Though we did not meet him, but he arranged a car for us.

The trek was difficult sometime. But we really enjoyed the trip. Whereas it is impossible for me to describe how it was in the hill, but let me just put few of the snaps taken by my friends.

Kanchenjunga

Picture Perfect


Few things which I found important for a novice trekker like me:
  1. Do a reality check, can you really trek? Don't just get carried away by what your friends say.
  2. Make sure you are not carrying anything redundant. Make your backpack as less as possible.
  3. Avoid shorter but difficult routes. Let it take some more time.
  4. Take a guide.
  5. Most importantly, you need a fit and strong health to trek.

Saturday, September 01, 2007

(useless) Stopwatch!

While reading this cheat sheet, I found a new stopwatch tool today. From your shell, you just run `time cat` to start the stopwatch. Once you are done, stop the clock by CTRL-D. Maybe it is not that useful, but I find it cool! It is geeky!