Wednesday, December 30, 2009

Friday, November 20, 2009

Some useful yet basic CSS

It might be some basic ones but sure has some day to day useful CSS functionality clearly explained.

Want to unit test your Statis classes? Power Mock to the Rescue

While reading through some articles on dzone i stumbled upon this google project which allows you to test your static methods. Now i have used easy mock which i integrated to our current project. But easy mock does not allow you to test static classes. It basically creates mock methods based on the interface you pass into it. This on the other hand will allow you to test your static methods which i believe is a very useful piece of tool for a developer. The project can be found here.

Wednesday, November 18, 2009

jQuery best practices and common mistakes

From recent times i have had a passion to learn jQuery which is the much talked about Java Script framework these days. Today i found these few articles which exlaines common mistakes we make when coding through jQuery and how to avoid them. I also found a pretty valuable piece of software called dynaTrance which allows you to monitor Ajax performance and find bottle necks just like profiling in java. The software can be found here.The articles which explains about the jQuery best practices can be found below;

Aricle 1

Article 2

Thursday, November 12, 2009

Marquee HTML tag

I was in need of doing a page which had a table to which content was written dynamically and with the need of horizontally manuvering it within the page. There were many help online but using varous JS frameworks. I did not want to be bombarded with frameworks as this was just a small thing. Luckly a colleuge of mine who is a major UI guru told me of the marquee html tag which allows me to accomplish this task very easily. Although this has been advised not to be used it is been supported by all browsers presently available. Below is my code snippet showing how i accomplished this.

<marquee id="scroller" scrollamount='2' direction='up' loop='true' height='450' width='100%' onmouseover='this.stop()' onmouseout='this.start()' title="Please move the mouse pointer away from the Display Area to start the Flight Display">
<table id='flightDisplayArea' width='100%' border='0' cellpadding='1' cellspacing='0'>

Friday, October 30, 2009

New MQ Released by JBoss

JBoss has released a Message Oriented Middleware component which also supports JMS 1.1 and is highly scalable with load balancing capabilities. More info can be found at the below link;
Should give it a try and see. If any of you guys have already used it please share your thoughts about this product.

Friday, October 16, 2009

InteliJ IDEA goes open source

This is superb news to all developers. Always loved developing in this editor and finally they have release a community edition. Superb. You can download it at the following link;
Happy developing every body :D

Tuesday, October 6, 2009

JBoss Caching Integration

JBoss caching is a very powerful caching mechanism developed and as far as i know this is the only Tree Cache implementation currently available. If i give a briefing on what caching is all about, caching allows you to minmize the time you go to the database to fetch data. We all know how costly database access is, and caching allows us to minmize those calls by caching the results fetched from the database. Ofcourse a general rule of thumb in caching is that you should always consider caching data that rarely change but frequently access.

There are many caching implementations out there, some being OSCache, EHCache, Teracotta (if im not mistaken this does allow caching as well) and many more are out there. I havent used these, but was involved in integrating OSCache at one point. OSCache is pretty much ok if your application is running on a single instance. When it comes to clustering, it becomes a bit complicated to configure OSCache. But still it is possible by the usage of Multicast addresses to publish cached data to multiple clusters but it is awfully complicated. And OSCache does not get involved in Transactions as far as i can remember. This is where JBoss caching comes in.

JBoss caching seamlessly integrated into a clustered environment with only a few configurations and most importantly it gets involved in Transactions and hence it only caches the data if the transaction successfully committs. And if your entities are updated within a transaction, so will the data in the cache be updated and works the same if rows are deleted from the database. Following I will show you how to integrate JBoss caching to your JBoss AS. I wanted to publish this article because although there was alot of documentation availabel on caching(JBoss does have comprehensive documentation) the information was dispersed so my intention of this article is to provide step by step operations to integrate JBoss caching. Following shows how to use JBoss caching with Hibernate.

Before i start explaining how to integrate JBoss caching there are some details you need to be aware of.

  1. JBossCache versions prior to 1.2.2 are not recommended for use with Hibernate, due to deadlock issues that may arise.
  2. Hibernate versions prior to 3.0.2 are not recommended for use with JBossCache, for the same deadlock issues mentioned above.
  3. Hibernate >= 3.2 is required if you plan to use Optimistic Locking. JBoss Cache >= 3.0.0 and Hibernate >= 3.3.0 is your optimal configuration, using MVCC as a locking scheme on JBoss Cache.
Im using Jboss cache 1.4.1 with Hibernate 3.2 so that i can use the Optimistic Locking feature provided.

The above list was taken from the Jboss wiki. Please have a look at the configuration table provided in that too to find the optimal configuration suited for you.

First of all you need to get the jboss caching distribution. Extract the jboss-cache.jar and jgroups.jar from that distribution as thats all you need. Im currently using jboss caching 1.4.1 with JBoss AS 4.2.2 GA. Place these two jars withing your deployment lib folder. For example /yourjbosslocation/server/default/lib. If you are using the "all" distribution the jgroups.jar will already be available to you. But in production you will almost always have your won deployment configuration.

Afterwards you need to define your caching implentation to be loaded as a service as MBeans. The following is the xml file ejb3-entity-cache-service.xml which you can find in your "all" configuration. The following file is edited a bit to include optimistic features.

<?xml version="1.0" encoding="UTF-8"?>

<!-- ============================================================ -->
<!-- Clustered entity cache config for use with JBoss Cache 1.4.x -->
<!-- ============================================================ -->
<mbean code="org.jboss.cache.TreeCache"


<!-- Name of cluster. Needs to be the same on all nodes in the clusters,
in order to find each other -->
<attribute name="ClusterName">${}-EntityCache</attribute>

<!-- Configure the TransactionManager -->
<attribute name="TransactionManagerLookupClass">org.jboss.cache.JBossTransactionManagerLookup</attribute>

Node locking level : SERIALIZABLE
<attribute name="IsolationLevel">REPEATABLE_READ</attribute>

Note that this will ignore the Isolation Level parameter if OPTIMISTIC is used
Node locking scheme:
<attribute name="NodeLockingScheme">OPTIMISTIC</attribute>

<!-- Valid modes are LOCAL
<attribute name="CacheMode">REPL_SYNC</attribute>

<!-- Must be true if any entity deployment uses a scoped classloader -->
<attribute name="UseRegionBasedMarshalling">true</attribute>
<!-- Must match the value of "useRegionBasedMarshalling" -->
<attribute name="InactiveOnStartup">true</attribute>

JGroups protocol stack config in XML format.

On Windows machines, because of the media sense feature
being broken with multicast (even after disabling media sense)
set the UDP.loopback attribute to true
<attribute name="ClusterConfig">
<UDP mcast_addr="${jboss.partition.udpGroup:}"
down_thread="false" up_thread="false"/>
<PING timeout="2000"
down_thread="false" up_thread="false" num_initial_members="3"/>
<MERGE2 max_interval="100000"
down_thread="false" up_thread="false" min_interval="20000"/>
<FD_SOCK down_thread="false" up_thread="false"/>
<FD timeout="10000" max_tries="5" down_thread="false" up_thread="false" shun="true"/>
<VERIFY_SUSPECT timeout="1500" down_thread="false" up_thread="false"/>
<pbcast.NAKACK max_xmit_size="60000"
use_mcast_xmit="false" gc_lag="0"
down_thread="false" up_thread="false"
<UNICAST timeout="300,600,1200,2400,3600"
down_thread="false" up_thread="false"/>
<pbcast.STABLE stability_delay="1000" desired_avg_gossip="50000"
down_thread="false" up_thread="false"
<pbcast.GMS print_local_addr="true" join_timeout="3000"
down_thread="false" up_thread="false"
join_retry_timeout="2000" shun="true"
<FRAG2 frag_size="60000" down_thread="false" up_thread="false"/>
<pbcast.STATE_TRANSFER down_thread="false" up_thread="false" use_flush="false"/>

<!-- The max amount of time (in milliseconds) we wait until the
initial state (ie. the contents of the cache) are retrieved from
existing members.
<attribute name="InitialStateRetrievalTimeout">17500</attribute>

<!-- Number of milliseconds to wait until all responses for a
synchronous call have been received.
<attribute name="SyncReplTimeout">17500</attribute>

<!-- Max number of milliseconds to wait for a lock acquisition -->
<attribute name="LockAcquisitionTimeout">15000</attribute>

<!-- Name of the eviction policy class. -->
<attribute name="EvictionPolicyClass">org.jboss.cache.eviction.LRUPolicy</attribute>

<!-- Specific eviction policy configurations. This is LRU -->
<attribute name="EvictionPolicyConfig">
<attribute name="wakeUpIntervalSeconds">5</attribute>
<!-- Cache wide default -->
<region name="/_default_">
<attribute name="maxNodes">5000</attribute>
<attribute name="timeToLiveSeconds">1000</attribute>
<!-- Caching region for Seating related entities. Will remain for 2hours before eviction -->
<region name="/mycache/Seating">
<attribute name="maxNodes">10000</attribute>
<attribute name="timeToLiveSeconds">7200</attribute>




The above file needs to be put in your "deploy" folder so that the caching service can find the configuration. In the above you can see I have used the "NodeLockingScheme" attribute and set it to "OPTIMISTIC". This is what allows for OptimisticLocking to take palce. Note that this will only work if you are using Hibernate 3.2. Else you should use the "IsolationLevel" attribute. In this same file i have defined that attribute as well but as i have used the "NodeLockingScehem" attribute, which overrides the "IsolationLevel" attribute. And if you look at the "CacheMode" attribute i have set it to "REPL_SYNC". If you look at the JBoss wiki link i have given above it states the following;

  1. If you are only using a query cache or collection cache, use REPL_ASYNC.

  2. If you are only caching entities, use INVALIDATION_SYNC

  3. If you are using a combination of query caching and entity caching, use REPL_SYNC.

Hence my use case is that i will be using query and collection cache as well as entity cache and hence REPL_SYNC is the ideal configuration.

Afterwards i want to move your focus to the region tags specified within the xml configuration above. If you only keep the default region then what happens is all the caching will be stored in one specifc region. If its entity caching then it will be stored in the default region with the fully qualified class name. Hence it is always best to separate your caching regions on entity basis or whatever basis you deem appropriate. One thing to keep in mind is to provide a meaningul eviction time as you do not want to keep your data forever in the cache. I have defined one caching region in the above configuration. I will next show you how to map this region name in your entity class. Below i give you the entity bean class which shows how to enable caching at the entity level.


import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.QueryHint;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

* Description : Seat Occupancy
* @author Dinuka
@Table(name = " SEAT_OCCUPANCY")
public class SeatOccupancy extends Persistent implements Serializable {

private static final long serialVersionUID = -4339488117889231833L;

@SequenceGenerator(name = "SEAT_OCCUPANCY", sequenceName = "SEAT_OCCUPANCY")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEAT__SEQ_OCCUPANCY")
@Column(name = "SEAT_OCCUPANCY_ID")
private Long SeatOccupancyId;

@Cache (usage=CacheConcurrencyStrategy.TRANSACTIONAL,region="Seating")
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "SEAT_OCCUPANCY_CHAR", joinColumns = { @JoinColumn(name = "SEAT_OCCUPANCY_ID") }, inverseJoinColumns = { @JoinColumn(name = " CHARACTERISTIC_CODE") })
private List<SeatCharacteristic> seatCharacteristic = new ArrayList<SeatCharacteristic>();

@OneToMany(mappedBy = "seatOccupancy", cascade = CascadeType.ALL)
private List<SeatOccupancyDetail> seatOccupancyDetail = new ArrayList<SeatOccupancyDetail>();

* @return the seatOccupancyId
public Long getSeatOccupancyId() {
return SeatOccupancyId;

* @param seatOccupancyId the seatOccupancyId to set
public void setSeatOccupancyId(Long seatOccupancyId) {
SeatOccupancyId = seatOccupancyId;

* @return the seatCharacteristic
public List<SeatCharacteristic> getSeatCharacteristic() {
return seatCharacteristic;

* @param seatCharacteristic the seatCharacteristic to set
public void setSeatCharacteristic(List<SeatCharacteristic> seatCharacteristic) {
this.seatCharacteristic = seatCharacteristic;

* @return the seatOccupancyDetail
public List<SeatOccupancyDetail> getSeatOccupancyDetail() {
return seatOccupancyDetail;

* @param seatOccupancyDetail the seatOccupancyDetail to set
public void setSeatOccupancyDetail(List<SeatOccupancyDetail> seatOccupancyDetail) {
this.seatOccupancyDetail = seatOccupancyDetail;


Here i have done a collection caching. You need to defined the usage and the region. If you do not specify the region it will be stored in the default region as i mentioned before. You may have noted that i have only said the region name to be "Seating" but in the configuration file which was shown before it said "/mycache/Seating". If you are caching a collection of objects please note that you should define that specifc entity as cacheable too. This brings us to the next topic which defines an entity to be cacheable.

public class SeatCharacteristic implements Serializable {



And if you want to use query caching here is how you would go about doing it.

//For Named Queries
@NamedQuery(name = "findAllSeats", query = "from SeatOccupancy", hints = { @javax.persistence.QueryHint(name = "org.hibernate.cacheable", value = "true") }),

//For Normal Queries
Query allSeats = session.createQuery("from SeatOccupancy so");

One thing to note here is that if you are using the "JOIN FETCH" statement in your queries do not cache those as the caching wont work for those kind of queries.

Lastly there is one last step to compelte the integration. You need to tell hibernate that you want to enable 2nd level caching and that you are going to be using the JBoss caching implementation. Provide the following parameters in your persistence.xml file or .hbm file.


<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
<!-- Clustered cache with TreeCache -->
<property name="cache.provider_class" value="org.jboss.ejb3.entity.TreeCacheProviderHook"/>
<property name="treecache.mbean.object_name" value="jboss.cache:service=EJB3EntityTreeCache"/>
<property name="hibernate.cache.region_prefix" value="mycache"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.cache.provider_class" value="org.jboss.ejb3.entity.TreeCacheProviderHook"/>
<property name="hibernate.treecache.mbean.object_name" value="jboss.cache:service=EJB3EntityTreeCache"/>

Now i come back to the part of why we only defined the region name in the previous entity as only "Seating". Its because we have given the "hibernate.cache.region_prefix" property the value "mycache" and hence the region will always be relative to "/mycache". And of course you need to tell hibernate to enable second level and query caching which is stated above. And the other properties are self explaining as far as i can see.

Well folks, thats about it on how to integrate JBoss caching to your Jboss AS. If you come acorss any difficulties please do contact me as i would very much like to help you.

Monday, October 5, 2009

Few SQL Select Tips

Was working on a Jasper report and i was able to learn some new SQL select options which i didnt know of and thought to share it with  you guys.
1. To concatinate fields to one column use the following;
    SELECT a.last_name || ' ' || a.first_name || ' '  as pax_name from Passenger a
2. To put a condition within the select statement use the following;
    SELECT  a.checking_sequence_number as seq_no,a.seat_no,
               WHEN booking_status = 'STNDBY'
               THEN booking_status
               ELSE passenger_checkin_type
               END as checkin_type
      from Passenger a
What this does is it checks for the column called booking_status and if it is STNDBY then it selects that value for the column else it gets the value of the column called passenger_checking_type.

Tuesday, September 29, 2009

An API to store primitive types in Collections

Found a project on source forge which allows you to store primitive data types within collections. What this does is consume less memory. You can find the project at the following link.

Spring Mail API Wrapper

Recently it was needed at my working place to have a module to send SMTP mails. I found out that Spring provides a nice wrapper around the Java Mail API so you do not need to deal with boilerplate code. Hence after a few hours of Googling and coding I was able to come up with an API which sends mail using Spring. Following I give you the code snippets required.

package com.test.commons.mailservices.core.remoting.ejb.service;

import com.test.commons.mailservices.core.exceptions.MailSenderException;

public interface MailSenderService {

* This method sends the mail to multiple recipients with the given subject
* @param mailMsg The message needed to be send as plain text
* @param recipientAddresses The mail addresses in an array to which the mail has to be sent
* @param subject The subject of the mail to be sent
* @throws MailSenderException this exception wraps the MailException throw by the Spring framework
public void sendMessage(String mailMsg,String[] recipientAddresses,String subject)throws MailSenderException;

* This method sends the mail to a single recipient with the given subject
* @param mailMsg The message needed to be send as plain text
* @param recipientAddresses The mail addresses in an array to which the mail has to be sent
* @param subject The subject of the mail to be sent
* @throws MailSenderException this exception wraps the MailException throw by the Spring framework
public void sendMessage(String mailMsg,String recipientAddress,String subject)throws MailSenderException;

* This method sends the mail to multiple recipients which are given as comma separated values, with the given subject
* @param mailMsg The message needed to be send as plain text
* @param recipientAddresses The mail addresses in an array to which the mail has to be sent
* @param subject The subject of the mail to be sent
* @throws MailSenderException this exception wraps the MailException throw by the Spring framework
public void sendMessageWithCommaSeparatedMailAddresses(String mailMsg,String recipientAddress,String subject)throws MailSenderException;

This is the main contract which any calling party can use to send mails. The method is overloaded so that clients can call with different functionality. Next I show you the implmentation of this interface as well as the exception class that i have defined which wraps the MailException thrown by Spring. I wrapped it so that any calling party only needs to know about the MailSending module and not about Spring exceptions.


import org.apache.log4j.Logger;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;

import com.test.commons.mailservices.core.exceptions.MailSenderException;
import com.test.commons.mailservices.core.remoting.ejb.service.MailSenderService;

* This is the Main class involved in sending email message to the outside world<br>
* The class uses the Spring Framework which wraps the java mail API to send mails.
* Common functionality of obtaining a SimpleMailMessage object is given by the parent<br>
* class named MailSenderCommon. The instance variables of the class are instantiated with<br>
* through a spring config. The spring config file responsible is mailconfig.spring.xml found <br>
* under the resources directory.
* @author dinuka
public class MailSenderImpl extends MailSenderCommon implements MailSenderService {

private static final Logger log = Logger.getLogger(MailSenderImpl.class);

private MailSender mailSender;

private String fromAddress;

public MailSenderImpl() {


* {@inheritDoc}
public void sendMessage(String mailMsg, String[] recipientAddresses, String subject)throws MailSenderException {
if (mailMsg == null || recipientAddresses == null) {
log.error("Input parameters received for sendMessage(String,String[]) are null");

sendEmail(mailMsg, subject, recipientAddresses);


* {@inheritDoc}
public void sendMessage(String mailMsg, String recipientAddress, String subject)throws MailSenderException {
if (mailMsg == null || recipientAddress == null) {
log.error("Input parameters received for sendMessage(String,String) are null");
throw new IllegalArgumentException("Received Input Parameters Are Null");
sendEmail(mailMsg.trim(), subject, recipientAddress);

* {@inheritDoc}
public void sendMessageWithCommaSeparatedMailAddresses(String mailMsg, String recipientAddress, String subject)throws MailSenderException {

if (mailMsg == null || recipientAddress == null) {
.error("Input parameters received for sendMessageWithCommaSeparatedMailAddresses(String,String) are null");
throw new IllegalArgumentException("Received Input Parameters Are Null");
sendEmail(mailMsg, subject, recipientAddress.split(","));


public MailSender getMailSender() {
return mailSender;

public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;

public String getFromAddress() {
return fromAddress;

public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;

private void sendEmail(String mailMsg, String subject, String... address)throws MailSenderException {

try {
mailSender.send(getSimpleMessage(mailMsg, fromAddress, subject, address));
} catch (MailException ex) {
log.error("MailSenderImpl: sendMessage() Exception occured" + ex.getMessage());
throw new MailSenderException(ex.getMessage());



import java.util.Date;

import org.springframework.mail.SimpleMailMessage;

public class MailSenderCommon {

* This is the common method which creates a simple message object which is used to send mails out
* Note that var arg is used as the second parameter to facilitate String[] and normal String object parsing
* to the same method. Also please note that you should always keep the var arg parameter as the last parameter in
* this method as the specification requires it.
* @param mailMsg
* @param addresses
* @return
protected SimpleMailMessage getSimpleMessage(final String mailMsg, final String fromAddress,String subject,final String... addresses) {
SimpleMailMessage message = new SimpleMailMessage();
message.setSentDate(new Date());

return message;


package com.test.commons.mailservices.core.exceptions;

public class MailSenderException extends Exception{

private static final long serialVersionUID = -6281925344129197510L;

private String message;

public MailSenderException(String message){
this.message = message;

public String getMessage() {
return message;

Then we have the SMTP Authenticator class which is used for mail authentication. It is as follows;


import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class SmtpAuthenticator extends Authenticator {
private String username;
private String password;

public SmtpAuthenticator(String username, String password) {
this.username = username;
this.password = password;

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);


And finally you the following spring xml shows how to configure and integrate all this together.

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=""

<!-- our Authenticator implementation -->
<bean id="smtpAuthenticator"


<!-- now setup an authenticated session -->
<bean id="mailSession" class="javax.mail.Session"
<prop key="mail.smtp.auth">true</prop>
<!-- <prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.socketFactory.class">
<prop key="mail.smtp.socketFactory.fallback">
</prop> -->
<constructor-arg ref="smtpAuthenticator" />

<bean id="mailService" class="">
<property name="mailSender" ref="mailSender"/>
<property name="fromAddress">

<!-- Mail service -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host">
<property name="port">
<property name="username">
<property name="password">
<property name="session" ref="mailSession" />
<property name="javaMailProperties">
<!-- Use SMTP-AUTH to authenticate to SMTP server -->
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.sendpartial">true</prop>
<!-- Use TLS to encrypt communication with SMTP server -->
<!-- <prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.smtp.sendpartial">true</prop> -->



As you can see i have used parameters as ${var_name}. This is because i have used Spring property file loading mechanism. Hence those variables are taken from a .property file. To configure that use the following;

<bean id="PropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
The order of these properties files is important, as properties
will override one another

Thats about it. Hope this would be helpful to someone who is looking to do the same.

Monday, September 21, 2009

A replace all string function for javascript

function replaceAll(strVal){ var regEx = /test/g; return strVal.replace(regEx,"test1"); }

What this does is replace all words "test" with "test1". If you do not want to add it globally and only want a replaceFirst method then just removed the letter "g" appended to the end of the "regEx" variable. That letter is the one that says to apply the regex globally.

Friday, September 18, 2009

Adding / Removing Options In A Combo Box

This JS function removed all options in a combo box except the first entry. If you want to remove the first entry as well then change the i>0 to i>=0

function removeExistingOptions(selBox){
          var i;
          for (i = selBox.length - 1; i>0; i--) {


The following function adds options to an existing combo box.

function addOptions(selBox){  

        var opt1=document.createElement('option');
        var opt2=document.createElement('option');

            // standards compliant
            // IE only


In both functions you have to pass the select element as the reference to the function.

DOM Manipulation In Tables

I was playing around with DOM manipulations in html tables and i wanted to add and remove table rows dynamically. In the end with the help of W3C school i was able to come up with a solution. Below is what i came up with in the end.

                var msgDetailsTable = document.getElementById("msgTable");
                var x = msgDetailsTable.insertRow(1);
                var y=x.insertCell(0);
                var z=x.insertCell(1);
                y.innerHTML="<font>    Line  :</font>";
                z.innerHTML="<textarea rows='4' cols='100' id='msgTxtArea' name='msgTxtArea' readonly='readonly'></textarea>";

This deletes the second row and then adds two new different <td> elements setting its widths as appropriate. This will work on Fire fox 1.5+ and all IE browsers.

Thursday, September 17, 2009

How to install jvmstat on linux

To install jvmstat on linux follow the below instructions;

1. Create a directory where you want to install jvmstat
2. Download jvmstat from
3. Unzip the distribution to the directory you created in the first step.
4. Change your PATH settings as follows; PATH=$PATH:/path_to_your_unziped_distribution/bin
5. Set the environment variable: export JVMSTAT_JAVA_HOME=/your_jdk_installation_path
6. Create a policy file called jstatd.policy with the following entry:

       grant codebase "file:${java.home}/../lib/tools.jar" {

Thats about it. And your ready to use jvmstat. Just type "jps" and you will get a list of java applications running on your machine. Then just use that id and type "visualgc PID" to run visualgc which will give you an overview of memory allocations on the heap by your application.

More info on how to do remote monitoring can be found in the below link;

A nice Garbage collection monitoring tool

jvmstat and visualgc is used to monitor application's Garbage collection. A very useful combination of tools to find memory leaks and the sort as I see it.

The JVM and how it handles stack and heap spaces

A recent discussion was going on about whether we should be using variables with a for loop or not. Going on those lines i stumbled upon a few articles explaining about the same.

A key point noted in the first post is
"The JVM specification that says that a JVM uses a fixed-size array for storing the values of local variables used in a method and each local variable maps to an index in this array. A Java compiler calculates the size of this array during the compilation of a method and declares it in the generated bytecode for the method."

So looking at that we can say that we do not necessarily need to worry about space allocation when thinking in terms of local variables as it is pre defined at compile time and is stored in a fixed-size array. Hence even if you create a String within a for loop, only one space allocated within that fixed-size array will be used. And according to the last forum post, the last comment sums it all up;

  • Class objects, including method code and static fields: heap.
  • Objects, including instance fields: heap.
  • Local variables and calls to methods: stack

  • But one thing to note is that in Java 6 some objects maybe created on the stack
    due to the "escape analysis" optimization used within Java 6. More info on that can be found at;

    Friday, September 11, 2009

    Java is always pass by value

    Interestingly enough after 2 years in the IT industry only today i knew that java was always pass by value. Meaning even if you pass an object to a method basically a copy of the value of the reference(basically the memory address) is passed to the method. The below article elbaorates on this even more.

    CVS code commenting templates in eclipse

    This article explains how you can integrate some code commenting templates which you can use when committing your code to CVS. Pretty useful.

    Wednesday, September 9, 2009

    Tuesday, September 8, 2009

    Java Heap Size Vs Native Memory Space

    Found a pretty interesting article explaing what causes out of memory exceptions to fire, how java heap space and native memory is used by an application.

    Saturday, September 5, 2009

    Test Driven Development (TDD)

    Been reading a bit on TDD recently and for some reason it has caught my attention. This is not something i have done ever in my kind of short carrier in IT :). But its a new concept for me and i kind of like how it looks at software developement. Hence it got my attetion.

    What TDD specifies is you write your unit test class first. You define the classes you may need. Of course at first your test will throwa Class not found exception when you run the test. But this is what TDD is all about. You write the minimal code required to get the test parsing. So what you do first afte running the test is you go create the implimentation class so that the test will compile and pass. And so and so forth you add functionality little by little and improve your design as you go foward. You always only implement the functionality you need to pass your test so it will help you save time and get a much cleaner code because you will be refactoring your code as you do your development and test it as well in the process. Not only will you end up with a nice looking code base, but it will be a well tested code base with much more code coverage.

    Ofcourse we know that most of the times we are dealing with database code within our codebase. But not to worry. EasyMock to the rescue. This framwork ( is able to mimick your database depenedent code, more specifically you DAO classes and is able to mock it so you do not need to create database connections within your test classes(which is a bad practice by it sef becaus then you will leave your database in an inconsistent state after running your tests). But one change or more over if your developing a component from scratch to note is you need to implement a setter method or constructor to swap in your DAO implementations at runtime so that we can swap in our mock implementation as we run the test to tell the code base to use our mock implementation at the time of running the JUnit tests. More info on how to configure EasyMock can be found in the below locations;

    TDD is pretty cool IMHO. Im gonna be trying it in my future development and see how it scales. If any of your are already using this methedlogy please share your comments. Would like to know all your views.

    Until my next post its adios from me again!!!!


    Thursday, September 3, 2009

    Terminator. A must have tool for developers on linux

    Pretty awesome tool which is able to open multiple command lines in one terminal. It increases productivity at least in a very small way and if you are running multiple servers at the same time this is a must have tool.

    Linux Permissions

    In linux the way we usually give permissions is by providing the command chmod 777 yourfile. This gives everyone read,write and execution privileges. But there is a better way to give permissions. Its as follows;

    chmod u=rx file (Give the owner rx permissions, not w)
    chmod go-rwx file (Deny rwx permission for group, others)
    chmod g+w file (Give write permission to the group)
    chmod a+x file1 file2 (Give execute permission to everybody)
    chmod g+rx,o+x file (OK to combine like this with a comma)

    Thanks Sanjeewa for the permission related info. One more thing he added was not to use the "cat"
    command but to use "less" to view files because when you use "cat" linux puts it in a memory
    buffer before displaying it on the screen.

    Singlish Converter

    Pretty cool tool to convert English to Sinhala. Have fun;

    Connect to other Linux machines with SSH and no password

    Check out this link which explains how you can ssh into a machine withouth providing the password.

    A JS Framework for application development

    Found a really nice JS Framework to support application development. Can be found at

    Its under LGPL as well. One important note in their site is abt JQuery.

    "Cappuccino is not designed for building web sites, or making existing sites more "dynamic". We think these goals are too far removed from those of application development to be served well by a single framework. Projects like Prototype and jQuery are excellent at those tasks, but they are forced by their nature to make compromises which render them ineffective at application development."

    Wednesday, September 2, 2009

    Some useful Eclipse Templates

    Found an aritcle describing some useful eclipse code templates. One thing which i found pretty useful was putting the isDebugEnabled check when doing debug level logging. The link can be found below;

    Tuesday, September 1, 2009

    JBoss and log4j

    Recently I got the following error when deploying my JBoss Application.

    log4j:ERROR Could not instantiate class [org.jboss.logging.util.OnlyOnceErrorHandler].
    java.lang.ClassNotFoundException: org.jboss.logging.util.OnlyOnceErrorHandler

    To see the problem was that the log4j and commons-logging jars which were already in JBoss was conflicting with the Jars I had on my war distribution. It was easily resolved after i removed the log4j and commons-logging jars from my war distribution and used those classes only to build the application because in runtime those jars are taken by defaults used within JBoss.

    Friday, August 28, 2009

    Cool memory analysing tool for eclipse

    Found a pretty cool tool to analyse heap dump files from within eclipse called Memory Analyzer. You can check for memory allocation and find out about your memory leaks, what processes are taking huge heap memory etc. More info can be found in the following links.

    The Perm Gen Exception in JBoss

    We sometimes get the PermGen runtime exception thrown from JBoss when running our app. Following in the lines of the exception i stumbled upon two very useful articles explaining the same. This can be found at;

    As it states Permanent Generation space is different from the Heap space we set using th -Xms commands as Perm Gen space is used to store class objects / method objects generated using reflection. As we use Hibernate this space is definitely growing with time and as the first post above says we should set the -XX:PermSize and -XX:MaxPermSize when running our app servers in order to minimize the risk of these exceptions occurring. You can also set the -XX:+HeapDumpOnOutOfMemoryError option to tell the VM to generate a heap dump if OutOfMemoryError is thrown.

    Wednesday, August 26, 2009

    Java EE 6 Is Out

    Wow some pretty cool features are out with the new Java EE 6 package. Nice post on the same can be found @

    Particularly I believe the Asynchronus type method invocation on Session beans is a pretty useful feature as some times we have to use MDBs to replicate the same kind of behaviour even though what we really need is just a non blocking call.

    Saturday, August 22, 2009

    Singleton not really singleton ??????

    The power of Java reflection is amazing. Check the following post on how you can even access Singleton classes and create new objects . Amazing...

    Tuesday, August 18, 2009

    Hibernate And Oracle User Defined Types

    I came across a situation recently where i had to use hibernate to read an Oracle defined object type which was used as a column type in the database. A friend of mine shared a useful link which explained how to do this using hibernate 2. But as we were using hibernate 3 I had to do a few adjustments to get it working. Following I share the procedures you need to follow in order to get hibernate 3 working with Oracle objects.
    First if you look at the Oracle object it self, it will look like something as given below;

    TYPE audit_trail as object






    Now to map this to a hibernate object first you need to create a DTO type class to hold the variables defined in the Oracle object. For this example i create a class called AuditTrail which represents the Oracle object.

    public class AuditTrail implements Serializable{

    private String updatedBy;

    private Date updatedOn;

    private String dmlAction;

    public AuditTrail(){



    * @param updatedBy the updatedBy to set


    public void setUpdatedBy(String updatedBy) {

    this.updatedBy = updatedBy;



    * @return the updatedBy


    public String getUpdatedBy() {

    return updatedBy;



    * @param updatedOn the updatedOn to set


    public void setUpdatedOn(Date updatedOn) {

    this.updatedOn = updatedOn;



    * @return the updatedOn


    public Date getUpdatedOn() {

    return updatedOn;



    * @param dmlAction the dmlAction to set


    public void setDmlAction(String dmlAction) {

    this.dmlAction = dmlAction;



    * @return the dmlAction


    public String getDmlAction() {

    return dmlAction;



    Then moving on you need to tell hibernate how to map the following class to the Oracle user defined type. We do this by implementing the interafce UserType which is provided by Hibernate.

    package com.test;

    public class AuditTrailUserType implements UserType {

    private static final int SQL_TYPE = Types.STRUCT;

    private static final String DB_OBJECT_TYPE = "AUDIT_TRAIL";

    public int[] sqlTypes() {

    return new int[] { SQL_TYPE };


    public Class returnedClass() {

    return AuditTrail.class;


    public boolean equals(Object o1, Object o2) throws HibernateException {

    if (o1 == o2) {

    return true;


    if (o1 == null || o2 == null) {

    return false;


    return true;


    private boolean equals(final String str1, final String str2) {

    return true;


    private boolean equals(final Date date1, final Date date2) {

    if (date1 == date2) {

    return true;


    if (date1 != null && date2 != null) {

    return date1.equals(date2);


    return false;


    public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner)

    throws HibernateException, SQLException {

    //assert names.length == 1;

    final Struct struct = (Struct) resultSet.getObject(names[0]);

    if (resultSet.wasNull()) {

    return null;


    final AuditTrail user = new AuditTrail();

    user.setUpdatedBy((String) struct.getAttributes()[0]);

    user.setUpdatedOn((Date) struct.getAttributes()[1]);

    user.setDmlAction((String) struct.getAttributes()[2]);

    return user;


    public void nullSafeSet(PreparedStatement statement, Object value, int index)

    throws HibernateException, SQLException {

    if (value == null) {

    statement.setNull(index, SQL_TYPE, DB_OBJECT_TYPE);

    } else {

    final AuditTrail user = (AuditTrail) value;

    final Object[] values = new Object[] { user.getUpdatedOn(),

    convertDate(user.getUpdatedOn()), user.getDmlAction()};

    final Connection connection = statement.getConnection();

    final STRUCT struct = new STRUCT(StructDescriptor.createDescriptor(DB_OBJECT_TYPE,

    connection), connection, values);

    statement.setObject(index, struct, SQL_TYPE);



    public java.sql.Date convertDate(Date date) {

    return date == null ? null : new java.sql.Date(date.getTime());


    public Object deepCopy(Object value) throws HibernateException {

    if (value == null) {

    return null;


    final AuditTrail user = (AuditTrail) value;

    final AuditTrail clone = new AuditTrail();




    return clone;


    public boolean isMutable() {

    return true;



    public Object assemble(Serializable arg0, Object arg1) throws HibernateException {

    return null;



    public Serializable disassemble(Object arg0) throws HibernateException {

    return null;



    public int hashCode(Object arg0) throws HibernateException {

    return 0;



    public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {

    return null;



    Then you need to define in your entity class how to map this class. You do this by using the columnDefinition tag in the @Column annotation. Following shows how you should map the Oracle user Defined type in your entity class.



    private AuditTrail auditTrail;

    Well thats about it. You can seamlessly integrate Oracle object handling with hibernate by following the few simple steps described above.

    Sunday, August 16, 2009

    Time for some realistic planning

    Ok so we have talked about iterative development, how to implements it then we got on to estimation and this post continues in that path to make it possible for you to provide reasonably realistic estimations and also talks about how to handle the customer when it comes to tight situations.

    So you and your team come up with an estimate for the whole project and guess what, the customer thinks its way too long. If you think of it in the customer's perspective what he/she wants is to get that competitive advantage that they perceive the software you are developing will produce in the market before any of their competitors do. We all know what kind of a competitive world we all live in so your customer is no exception. Of course there are few things you can do at this moment.

    First of all if you look back on how we made our previous estimation you could see we didnt take into account other overhead such as time spent on installations, updgrades, vacations, sick leaves, paper work etc. These all take considerable amount of time and you need to account for this in to your project estimation. Ok so now you will be asking how the **beep** are we gonna do that. Based on what? Ok chill chill. Variation to the rescue. Variation takes into account all the things that were stated before and counts for that. What is recommended is to have a Variation of 0.7 for a new project team. So how do you calculate the actualy number of days a developer will take to complete work within an iteration with the variation taken into account. Following is the calculation on how to do that;

    1(the number of developers) x 20(project iteration size) * 0.7 = 14 days(The actual amount of time to complete the work within one iteration)

    Multiply this by the number of iterations required for your first milestone and then you will get a realistic value on how many days are needed to complete the work. So now you have a realistic amount of days which your team feels confident about. Then you go to the customer and negotiate on what to do if this value is greater than the one he/she specified.

    What you can do in this instance is lay down your user stories and ask the customer to first of all prioratize them according as they deem appropriate from high to low. You can give them a variation of values to base them such as 10-50 where 10 being the highest priority and 50 being the lowest.

    After this is done you get this priority list and try to assign it to your iterations and see if you can get it everything in for the time specified. Something to note here is to assign the user stories according to the highest priority to the lowest. And one more thing is while doing this you should focus on only keeping your baseline functionality intact. Baseline functionality are the smallest amount of features that are needed to give a working solution to the customer.

    With this amount still if the estimation is higher than what the customer expects then you have to sacrifise some of the user stories and push them back on to the next mile stone. And sadly you will have to notify the customer of the reality of the situation. One thing to note is to specify to the customer on what basis you came into this estimation. Then they will in most cases understand where your coming from. But thing to note is to always be upfront and honest to your customers because customer loyality once lost can never even be regained as i see it. What you have to specify to the customer is that the other features are not scrapped out completely, its just that they will only be available for the next milestone. If the customer still wants all that functionality then the only possible way to do that is by extending the number of iterations in your project which will eventually bring up the project deadline. But it is always the case where the customer will agree on scrapping some of the fuctionality until the next milestone.

    In the end you have a realistically possible project due date that you feel confident about. And after all its better to under promise and over deliever and the vise versa. Hence you should be truthful about your estimation rather than building the project plan according to what the customer wants it to be which would only pave you a nice big path to failure :) .......

    Well happy estimating and keep your projects in line.... In line of success ;)

    Tuesday, August 11, 2009

    The Dreadful Estimates

    Well the title of this post it self is self explanatory aint it ;) ... We all know how hard it is to estimate something in our own lives. Moms will always ask how long will it take to clean your room, wife will ask how long will it take for you to get home, if you ask your dad for something he will ask how much does it cost.. So as the pattern goes on you can see all of us live in a world revolving around estimates. The same comes into play when estimates need to be made when an IT project is taken into consideration. Ofcourse all of us know how much of a dreaded task estimations can be mostly due to the fact of uncertainity that is filled with making some or most of the estimates. Aim of this post is to help all you poor souls and to take you out of your misery of doing estimates and doing them right:D ..

    First of all what needs to be done is basically jot down all the user requirements and break them up into user storys which refelect all the functionality which needs to be provided by the software we are doing to build. A user story can be just a short 3-4 line description of what the functionality is all about with a title preceding. For example a typically user story will look like the following;

    Title - Log-in users to the system
    Description - Provide authentication capabilities to users loggin in to the system via a login menu.

    That of course is one simple user story but you get what im trying to imply here yea ;) ... Ok so moving on, the next thing to do is to get together with your team with all the user storys you have come up with after many initial discussions with the customers and to decide an appropriate estimate for each user story you have defined.

    One fun way of doing this would be by putting the user story on the table, explaining to your team what is exactly required by the user story and ask each one to provide an estimate of how long it will take to finish that specif story. Then you look at the spread of values taking everything into consideration. You then ask each developer based on what assumptions each of them came up with the estimates. What you do then is clarify each assumption with the customer that your team has come up which even you cant provide an accurate answer. Note that this is a pretty important step because if you go ahead with many assumptions to the coding stage that runs a high risk factor of the resulting software not being what the customer really wanted. Hence it is always advisable to talk to the customer up front with any assumptions you have and to get it clarified at that point of time so as to minimise the risk factor.

    But of course at times even the customer would not know the correct answer to an assumption in which case what you should be doing is noting it down so that you have a track of any risk factors associated with each user story.

    Then after going through the cycle of estimation and assumption clarification you ask your team to make another estimate now that most of the assumptions are resolved. Then you take the spread of estimated values which in this case would not be as much dispersed as before and take an average value from those values and come to an agreement with your team members of that value. Ofcourse one thing to note is this time should include not only the coding time but also the design, testing, integration, documentation(if needed) and deployment time.

    If for some reason the estimated number of days for a user story is more than or equal to 15 days that usually means still there is something wrong somewhere. So what do you do in this situations? Well you got two options;

    1. Break down the user story into smaller functionalities, thereby spreading the number of days among the sub functionalities.
    2. There still might be unanswered assumptions that might fact for this estimate hence it is time to go back to the customer again and to further clarify those assumptions which would eventually lead you to re estimate the number of days.
    Hence any of the following two ways can be used. After that what you do is add up all the estimated values you have come up with for all the user storys which would then make it possible for you to give the customer an estimated for the whole project which you feel confident about because you and your team have nailed down almost all of the assumptions and are pretty confident with the estimate.

    So you come up with the estimate for the whole project. What if the customer says that the number you came up with is too much???? Yikes, didnt think of that now did ya? Well that my friend is a topic of its own. So stay tuned for the next post to see what you can do to overcome/handle such situations.

    Sunday, August 9, 2009

    Iterative Software Development Cont.....

    My last post gave an introduction to what iterative development is all about and what kind productivity and value addition it brings to the table. In this post i want to address the questions unanswered in my last post. Cant keep the readers in suspense now can i ;) ... But hey everybody likes a little thriller every now and them right? :) .... So what were the questioned that were unanswered in my last post? Ok ok if your bored to go back to it and check it out let me list it down here again :D....

    • How to approach iterative development
    • How to project your iteration size
    • How to incorporate new customer changes half way through an iteration
    Taking first thing first, the way you should ideally approach an iterative development process is by first analysing the initial customer requirements you gather and breaking down those features with respect to the application scope. Then what you should do is to weight every feature according to the priority level (High/Low) as perceived by the Customer and estimate the number of development days each feature will take to complete.

    This process includes the asnwere to our second question which is how to project your iteration size. So you can see them both as interelated questions. Iteration size normally is recommended to be best kept at 20 working days(i.e one calendar month). But ofcourse this is definitely a varying factor depending on the complexity and the size of the project.

    What you do after you decide on your iteration size is to try to calculate what features can be included in the first iteration which keeps in track with the iteration size you specify. But also you should keep in mind to put in most of the high priority tasks to each iteration as possible. Sometimes there maybe some low priority features that need to be provided before you can continue with a high prioratized feature in which case it is acceptable to include low priority features into an iteration.

    Going on to my last question which is what you do if the customer comes up with a new set of features while you are in the middle of one of your iteration. Again you should go in the normal flow as explained before and weight new features accordingly and then try to see how it best fits the current iteration. If it is possible you could always push back some of the planned features of the current iteration to the next iteration and incoporate the new features whilst keeping the iteration size intact. Then you could ask the question what if its the last iteration and the customer comes up with a new set of features. Well in this instance you have to come into an agreement with the customer as to what is realisticaly possible to achieve for the given deadline and either try to move the dead line or add more developers or ask the current team to work long hours to make the current deadline. But in my perpective i do not believe adding more developers or making the existing ones work long hours will do the project any good as overworking burns out developers which in turn will lessen their productivity in the long run. And adding new developers in the last iteration is or for that matter in the middle of the project is a very decisive decision to make because according to what is stated in the book The Mythical Man Month by adding new developers you are adding n(n-1) / 2 communications channles within the project where "n" is the number of people in the development team.

    Hence it is always best to try to negotiate with the customer on the current situation and try to shift the deadline to a latter date or to come to an agreement and compromise some features as deemed appropriate by the customer that can be included in later versions after the deadline.

    Well thats about it for now about iterative development. Two pretty long posts on iterative development huh?... :) .. Guess you guys are now getting sick of reading about iterative development. So ill try to blend in something different in my future posts to come.

    Until then its adios from my side and happy development (hopefully iteratively :D )

    Iterative Software Development

    Ive been wondering why sometimes we in our projects face tight dead lines and if there is any way we could overcome such situations. In my current project we are kind of facing a tight deadline situation as well and this led me to investigate on this topic of how the development process should be organised so that these kind of issues can be resolved before hand as much as possible.

    My eyes caught up on a process known as iterative development. For some this definitely is not a new concept, if so please do ignore this post :) . Iterative development as i see it is not necessarily a process by itself but we can incorporate it to any of our current processes in order to maximise efficiency and throughput.

    If we look at a project at a very basic level what needs to be done in order to complete it successfully is to develop a product/application which meets all/most of the user's needs within the time line given by the user and within the budget specified. How some people approach this kind of problem is by trying to figure out all of the customer requirements before even writing a single line of code or design document and spend a considerable amount of time in that process. But what they later find out is that customer requirements never stay static because of the fact that even the customer would not know what he wants as the project is initiated. What this kind of process results in is developing a product/applications which does not meet most of the user's needs because of the fact that we lose contact with the customer after the intial rigorous requirement gathering phace and only come into contact once we go through the full cycle of the the development process.

    But what we need to do is to break up whole project into smaller iterations and thereby do repetitive requirement,design,development,testing cycles in each iteration. What this kind of approach gives is the ability to get customer feed back after each iteration where the user can say if we are on track according to his/her needs or not and we can then refine our next iteration incorporating these changes. By following an iterative development process we surely are able to stay on track in most cases and meet the project deadlines without out burning the development team.

    More on how to approach iterative development and how to incorporate new customer changes half way through an iteration and how to project your iteration size can be seen in the coming articles... So stay tuned ;)

    Thursday, August 6, 2009

    JavaScript instance methods vs Class methods

    Javascript instance methods are those that start with the "this" keyword where as class methods start with the prototype keyword. The difference between the two is that given an object instance methods are created per object whereas class methods are only one per class and not per instance so you will avoid creating duplicate object methods. Examples of the two are as follows;
    1. Instance method example
        this.getName = function(){return;}
    2. Class method example
        //ObjName is the name of your object
        ObjName.prototype.getName = function(){return;}
    There is another method which is a class only method. The only difference with that is that it cannot access instance variables like the class method above but can only access class only variable. Example is as follows;
    //this is a class only variable = 'test';
    /*Note that to get the class variable you have to drill down to the prototype object and you cannot access instance variables in class only methods. Only difference between this and the previous method as you can see is that it does not include prototype keyword.*/
    ObjName.getName = function(){return;}
    But one thing to keep in mind is that the fact that the prototype keyword is not sometimes supported by older browsers.

    Wednesday, August 5, 2009

    Java Script Date Object

    Java script consist of a Date object which is kind of similar to the Java Date object where as it uses the time since the epoch but some utility method available in the Java language are not available in the JS Date object version. Some of the utility method which i cared to share are as follows;

    getDate() - Get the day of month e.g 1-31
    getMonth() - Gets the month of the year. Note that it starts with 0-11 So Jan is basically 0.
    getFullYear() - Gets the current year as a four digit character

    Also we can pass the date as a string literal to the date object as new Date("08/09/2007") which it will convert to the intended date time. It also consists of a toString method which is a bit too cryptic and should not be used when showing specific date objects. The above in-built methods should be used instead to show the user a properly formatted date.

    How do you get teh number of days between two days;

    This can be done as follows;

    //Assuming that date 2 is after date 1

    return Math.round( (date2-date1)/(1000*60*60*24));


    Java Script Array Sorting

    Java scripts have intrigued me!!!As so far as me going to the book store and selecting java script books to learn it the old fashioned "Off the shelf" way ;) ... So some of my posts from here onwards will contain a mix and match of java scirpt/java so any anti javascript ppl please dnt take it personally :D.... I never knew java script had array sorting like whats available for us java developers. Two ways this can be accomplished..

    Method 1:

    //Sorts values in descending order
    function compare(val1,val2){
    return val2-val1;

    var myarray = new Array([1,3,7,10,32,45]);

    Thats about it to do sorting using arrays. Of course you could have just used myarray.sort() which would have used the default sorting mechanism and sorted the array in ascending order. You could debate here saying why do we need to define a new method just to get the sorting done. Bit too much code to do a single sorting function. Well look no further method 2 below shows how to do the same thing as above with just one line of code using the function literal capability of Javascript.

    Behold Method 2!!!!!!! (Drum roll please)
    Method 2:

    Thats about it for now. But more to come very soon guys. So stay on the look out for all those Java script newbies like myself :).


    Sunday, August 2, 2009

    String concatenation and String builder confusions resolved

    There was a very hot debate going on about String vs String builder and doing string concatenation within the append method of the String builder. I then researched this topic on the net because i had to prove a point in my work area ;) ... Then i stumbled upon this great blog post which i thought i should share with all of you which clearly explains when and how to use these String concatenation methodologies. And thankfully i was right in my assumptions :D.... The blog post can be found at

    Friday, July 31, 2009

    @BatchSize() Annotation in hibernate

    While searching on the net on how to gain perfomance in JPA/Hibernate i stumbled upon an article written on hibernate annotation batchsize and it intrigued me on how it really works. After reading on and going through the algorythm defined by Hibernated on how it works i understood that this adds a sufficient perfomance gain in the event of you having large collections within your entities.

     --------Updated on 07/30/2012 according to the clarification given by Jeremy---------

    For example lets consider an Airport parent containing a collection of airlines as such;

        List<Airlines> airlines = new ArrayList<Airlines>();
    Imagine you had such a statement in one of your entities. Assume there can be 100 Airport objects at any given time.Without the BatchSize annotation, Hibernate will first retrieve the Airports separately and for each airport it will retrieve the airlines separately. Now consider the following code snippet;
       List<Airlines> airlines = new ArrayList<Airlines>();
    When you use the batch size annotation what hibernate does is it divides the number of elements that would come in the resulting query by the batch size defined. In this case its 100 / 16 so you get 6 and remainder 4. What this implies is hibernate will go to the database 6 times to fetch 16 Airport objects' with their Airlines collection initialized and then go again another time to retrieve the remaining 4 Airports again with their Airlines collection initialized. So what the @BatchSize does is decide how many collections should be initialized.

    Thursday, June 18, 2009

    Concurrent HashMap vs HashMap

    So today i looked into these two Map types to use in the multi threaded application im working on. It was really confusing to understand the exact differences between the two but after some research this is my vedict;

    Use ConcurrentHashMap if you only want to concurrently add and remove values and do not want to access the map while concurrent additions and modifications go on. But if you do want to access data while concurrent additions and modifications are going on then its better to use Collections.synchronizedHashMap() and make the iteration code block thread safe in order to avoid race conditions.

    Wednesday, June 17, 2009

    Simple Java Mail SMTP Client

    import java.util.Properties;

    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    class SimpleMail {
    static Message emailMessage;

    public static void main(String[] args) {

    try {

    emailMessage = new MimeMessage(createSession());
    // replace this with the TO mail address
    InternetAddress add = new InternetAddress("");
    InternetAddress[] addresses = new InternetAddress[1];
    addresses[0] = new InternetAddress("d");
    emailMessage.setSubject("My Subject ");
    emailMessage.setContent("My First Mail", "text/plain");


    } catch (AddressException e) {

    } catch (MessagingException e) {



    private static Session createSession() {

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("", "your_mail_server_IP");

    // If your sending multiple mails and even if one mail fails this by
    // setting
    // this property all the other mails except that mail will still be
    // delievered
    props.put("mail.smtp.sendpartial", "true");

    Authenticator authenticator = null;

    props.put("mail.smtp.auth", "true");
    // enter your mail address and password here
    authenticator = new MessagingAuthenticator("", "password");

    return Session.getDefaultInstance(props, authenticator);

    class MessagingAuthenticator extends Authenticator {
    private String userName;
    private String password;

    public MessagingAuthenticator(String userName, String password) {
    this.userName = userName;
    this.password = password;

    public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(userName, password);