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.

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

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());


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

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;

package com.jkcs.commons.mailservices.core.remoting.ejb.bl;

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="http://www.springframework.org/schema/beans"
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- 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="com.test.commons.mailservices.core.remoting.ejb.bl.MailSenderImpl">
<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 http://developers.sun.com/dev/coolstuff/jvmstat/
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" {
    permission java.security.AllPermission;

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 (http://easymock.org/) 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.