Monday, November 24, 2008

Daemon Threads in Java

Any Java thread can be a daemon thread. Daemon threads are service providers for other threads running in the same process as the daemon thread.

When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.

Daemon threads are sometimes called “service” threads. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. This thread is provided by the JVM.

The Thread Object

class HelloThread extends Thread {

public void run() {

try {

for ( ; ; ) { System.out.println("hello"); sleep(1000); }


catch(Exception e ){}


The normal thread

public class RegularThreader{public static void main(String[] args){
Thread hello = new HelloThread();
System.out.println("Sorry, I must be leaving destroy");

The Daemon Thread

public class DaemonThreader{

public static void main(String[] args) {

Thread hello = new HelloThread();


System.out.println("Sorry, I must be leaving");}}

Just the check the difference in the way ther run

1. In the first case the child thread runs continously

2. but the Daemon thread exits when the main thread is complete;

Thursday, November 20, 2008

Oracle Streams Advanced Queuing (AQ)

Advanced Queuing provides database-integrated message queuing functionality. Advanced Queuing leverages the functions of the Oracle database so that messages can be stored persistently, propagated between queues on different machines and databases, and transmitted using Oracle Net Services, HTTP(S), and SMTP.

You must set up the following data structures for certain examples to work:
CONNECT system/manager;
GRANT Aq_administrator_role TO aqadm;
Creating a Queue Table and Queue of Object Type
queue_table => 'TEST_TRANSACTION_TABLE',multiple_consumers => TRUE, queue_payload_type => 'TEST_TRANSACTION');
Adding subscriber to the queue
subscriber := SYS.AQ$_AGENT('SUDHEER', NULL, NULL);
SYS.DBMS_AQADM.ADD_SUBSCRIBER(queue_name => 'TEST_QUEUE',subscriber => subscriber);
Procedure to Enqueue
DECLAREmessage TEST_TRANSACTION;enqueue_options DBMS_AQ.enqueue_options_t;message_properties DBMS_AQ.message_properties_t;message_handle RAW(16);BEGINmessage := TEST_TRANSACTION('TESUSER',5,NULL);dbms_aq.enqueue(queue_name => 'TEST_QUEUE',enqueue_options => enqueue_options,message_properties => message_properties,payload => message,msgid => message_handle);
Java Agent to access Queue
public static void main(String args[]){

Connection connection = DriverManager.getConnection( "jdbc:oracle:thin:@", "ppokerops", "ppokerops");
AQSession aqsession = AQDriverManager.createAQSession(connection);
AQQueue queue = aqsession.getQueue("ppokerops","QUEUE1");
TransDAO data = null;
AQMessage message = queue.createMessage();
AQDequeueOption dq_option = new AQDequeueOption(); dq_option.setConsumerName("SUDHEER");
message = queue.dequeue(dq_option, Class.forName(""));
data = (TransDAO)message.getObjectPayload().getPayloadData();
} catch(Exception e) {

Thursday, November 13, 2008

Spring AOP Basics

The best atricle i have come across to start with Spring AOP
This can be followed by Spring tutorial from

Wednesday, November 12, 2008

Fetching Property Files Using Resource Bundle

Put the property Files in the classpath ,which contains key value pairs.
If the files are putin any other location thean classpath , give the path in tomcat or next to the bootstrap jar listing.
Now access the files as accessing any other Bundle
ResourceBundle myResources = ResourceBundle.getBundle("propertfilename");
Then u can do a bundle.getValue() to the required key value pair.


Apache XML-RPC is a Java implementation of XML-RPC, a popular protocol that uses XML over HTTP to implement remote procedure calls.
1.Client class
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(new URL(""));
XmlRpcClient client = new XmlRpcClient();
Object[] params = new Object[]{new Integer(33), new Integer(9)};
Integer result = (Integer) client.execute("Calculator.add", params);

2.Server Class
public class Calculator {
public int add(int i1, int i2) {
return i1 + i2;
public int subtract(int i1, int i2) {
return i1 - i2;

3. Create Propert File
Create a property file, which contains at least one property. The property name is arbitrary, and the property value is the fully qualified name of the Calculator class. For example, like that:
The property file must be called, and it must be located in the package org.apache.xmlrpc.webserver. In other words, you would typically put it into the directory org/apache/xmlrpc/webserver and add it to your jar file.

4. Add Entry to Web.xml
<servlet-name> XmlRpcServlet</servlet-name>
<description> Sets, whether the servlet supports vendor extensions for XML-RPC. </description>

XStream - Convert XMl to Java & Vice Versa

XStream is a simple library to serialize objects to XML and back again.
XStream xstream = new XStream();
Person joe = new Person("Joe", "Walnes");
String xml = xstream.toXML(joe)
The resulting XML looks like this:
Deserializing an object back from XML
Person newJoe = (Person)xstream.fromXML(xml);
Reference :

Saturday, November 1, 2008

Multiple Ajax Requests - Consequtively

When Ajax requests are submitted one after the other by hitting the same URL requests
will not be submitted by property of ajax requests, since it tries to stop multiple requests
being submitted .
This can be avoided by appending Date field with milliseconds to the url.
By doing so the Ajax identifies it as a different request and request will be re-submitted.

OSWORKFLOW - Workflow Engine

OSWorkflow is fairly different from most other workflow systems available, both commercially and in the open source world. What makes OSWorkflow different is that it is extremely flexible.
OSWorkflow can be considered a "low level" workflow implementation. Situations like "loops" and "conditions" that might be represented by a graphical icon in other workflow systems must be "coded" in OSWorkflow.

Almost all of the required libraries for OSWorkflow are included in the distribution:
OSCore 2.0.1+
PropertySet 1.2+
Jakarta commons-logging
BeanShell (optional)
BSF (optional)
EJB interfaces (not neccesarily an EJB container)
XML parser (Not required for JDK 1.4)

Various concepts in oSWorkFlow are
Workflow Definition
Workflow Concepts
Common and Global Actions
SOAP Support

JNotify - Java library that allows java application to listen to file system events

JNotify works on both Windows (Windows 2000, XP, Vista) and Linux with INotify support (Kernel 2.6.14 and above).

JNotify is a java library that allow java application to listen to file system events, such as:
file created.
file modified.
file renamed.
file deleted.
This property can be used in a number of scenarios.I have used it to reload resource bundles
whenever there is a modiofication in it.

Wednesday, September 24, 2008

Quartz - For Scheduling

Quartz is a full-featured, open source job scheduling system that can be integrated with,or used along side virtually any J2EE or J2SE application.It can mainly be used for Driving WrkFlow and System maintainance.
It can be integrated with any system with ease.It can perform simple or complicated schedules based on given cron expression.The execution logic can be embedded into simple java classes by implementing certain intefaces.
The job information can either be stored in memory through RAMJobStore or can be stored in relational databases using JDBCJobStore.If RAMJobStore is used whenever the server restarts, previously scheduled data is lost.
For scheduling jobs a scheduler needs to be started and jobs can be added as shown below.
SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
Scheduler sched = schedFact.getScheduler();
JobDetail jobDetail = new JobDetail("myJob", null, DumbJob.class);
Trigger trigger = TriggerUtils.makeHourlyTrigger(); // fire every hour trigger.setStartTime(TriggerUtils.getEvenHourDate(new Date())); // start on the next even hour trigger.setName("myTrigger");
sched.scheduleJob(jobDetail, trigger);
Custom job should implement the following interface
Job Interfacepackage org.quartz;
public interface Job {
public void execute(JobExecutionContext context) throws JobExecutionException; }
CronTrigger needs to be used for more complicated schedules.
An example of a complete cron-expression is the string "0 0 12 ? * WED" - which means "every Wednesday at 12:00 pm".

Thursday, September 11, 2008

Writing Simple Taglibs

Writing tag libraries has mainly 3 parts

1 .The tld file defining the tag parameters

2. Java Class Containing the implementation of the Tag

3. Jsp Code Calling the Taglib

1.Tld for Tag

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
<info>OReilly Sample Tag library</info>

<tagclass>com.ivy.tags.Hello </tagclass>

This is a simple hello tag.




2.Java Class For the Tag

public class Hello extends BodyTagSupport {
private String name=null;
private int iterations=1;

* Getter/Setter for the attribute name as defined in the tld file
* for this tag - Name & iterations

//core content of the tag needs to be written here

public int doStartTag() throws JspTagException{
try {
JspWriter out = pageContext.getOut();
out.println("<table border=\"1\">");
if (name != null)
out.println("<tr><td> Hello " + name + " </td></tr>");
out.println("<tr><td> Hello World <td></tr>");
} catch (Exception ex) {
throw new JspTagException("All is not well in the world." + ex );
// Evaluate the body if there is one

//For the end part execution

public int doEndTag() throws JspTagException {
try {
JspWriter out = pageContext.getOut();
} catch (Exception ex){
throw new JspTagException("All is not well in the world." + ex);

public int doAfterBody() throws JspTagException {
if (iterations >= 1) {
BodyContent body = getBodyContent();
try {
JspWriter out = body.getEnclosingWriter();
body.clearBody(); // Clear for next evaluation
} catch(IOException ioe) {
throw new JspTagException("Error in Hello tag doAfterBody " + ioe);
} else {


Include the written tld <%@ taglib uri="./sample.tld" prefix="sample" %>

<sample:hello name="userName" iterations="5">
<tr><td><b>Have a nice day</b></td></tr>

CSS Sprite - Another Web Optimisation Technique

When there are lots of images to be downloaded for a web page, the best option would be to use Css Sprite.In simple
words it reduces the number of images to be downloaded into one single big image.

Thus all the image requests will be reduced into one single request.At slight cost of increase in size better performance is attained.

Different Technique can be used to a create a single image from multiple images. The single image needs to be mentioned in the css and
where the individual images are required in the jsp the big image is specified with the offset, which cuts off the unwanted part of the image.


Multiple images before Sprite

#nav li a {background:none no-repeat left center}
#nav li a.item1 {background-image:url('../img/image1.gif')}
#nav li a:hover.item1 {background-image:url('../img/image1_over.gif')}
#nav li a.item2 {background-image:url('../img/image2.gif')

Sungle Image with Sprite & offsets mentioned for each image

#nav li a {background-image:url('../img/image_nav.gif')}
#nav li a.item1 {background-position:0px 0px}
#nav li a:hover.item1 {background-position:0px -72px}
#nav li a.item2 {background-position:0px -143px;}

The website provides interface which can take in images uploaded as zip and convert into a single image.

Wednesday, August 13, 2008

Symbolic Links

There are two concepts of `link' in Unix, usually called hard link and
soft link.

A soft link (or symbolic link, or symlink) :it is a small special file that contains a pathname. Thus,
soft links can point at files on different filesystems


To create Soft link
ln -s [target] [linkname]

Delete links
rm [link name]

Display Links
ls -l

A hard link is just a name for a file. (And a file can have several names). It is deleted from disk only when the last name is removed. Hard link can be created without the -s option.

The major use of links would be to avoid redundancy and it saves a lot of maintenance headaches.A typical case would be to avoid redudant image copy into multiple locations . Instead create symbolic links. Changing one image serves the need , if not links can be overridden with location specific image.

Monday, August 11, 2008

Direct Web Remoting (DWR)

Direct Web Remoting (DWR) exports java code to the browser. It consists of:
A java servlet running on the server that processes requests and sends responses back to the browser

Javascript running in the browser sends requests and can dynamically update the webpage

Methods for installtion

1 .Download the DWR jar

2. Addition into web.xml
<display-name>DWR Servlet</display-name>

3.Add dwr.xml
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
<create creator="new" javascript="JDate">
<param name="class" value="java.util.Date"/>
<create creator="new" javascript="Demo">
<param name="class" value=""/>

The DWR config file defines what classes DWR can create and remote for use by Javascript
http://localhost:8080/[YOUR-WEBAPP]/dwr/ will show all accesible java methods

Include links to the javascript files that make the magic happen:
<script src='/[YOUR-WEBAPP]/dwr/interface/[YOUR-SCRIPT].js'></script>
<script src='/[YOUR-WEBAPP]/dwr/engine.js'></script>

DWR generates Javascript code that is similar to the Java code that exported using dwr.xml


public class Remote {
public String getData(int index) { ... }

<script type="text/javascript"
src="[WEBAPP]/dwr/interface/Remote.js"> </script>
<script type="text/javascript"
src="[WEBAPP]/dwr/engine.js"> </script>

Remote.getData(42, function(str) { alert(str); });

It also helps in calling Meta-Data Objects ,handling Timeouts and Handling Errors and creating Creating Javascript objects to match Java objects.
Hence the java objects can be mapped to javascript and exchanged vise versa.

For more info refer : -

Wednesday, August 6, 2008

Web Performance Techniques

1. Zipping the static content(images,css,javascript) and page response.

This can be achived by using the following configuration on the apache vhost configuration

For static content

<FilesMatch "\.(html|htm|js|css)$">
SetOutputFilter DEFLATE

For page response ending with .do requests

<LocationMatch "\.(do)$">
SetOutputFilter DEFLATE

2. Adding expires header

<FilesMatch "\.(jpg|jpeg|png|gif|swf)$">
Header set Expires "Wed, 31 Dec 2008 23:59:59 GMT"

Expires also can be set as access plus x days

By adding this all images with the above extensions will not be requested.

If the above is missing all requests are made and images are downloaded for every requests.

if the browser cache is enabled , still Get requests are made and if the response is 304 meaning file has not changed the image will not be downloaded else
will download the image.

3. KeepAlive On

KeepAliveTimeout 15

MaxKeepAliveRequests 100

By setting this on httpd.conf the connection once obtained will not be disconnected until 15 seconds. Hence the multiple requests on a page will be faster.
The disadvantage could be , if the requests are very high the latter once will not get a connection until these are closed.

The cache setting will override the expires header setting, if it is less than the time interval for expires header.

Must use Addons With FireFox

FireBug - Shows request basis data along with headers and allows easy debugging of html content.

Web developer - Comes with lot of web development features like enable/disable cache/image/css/form data/proxy etc.

Live HTTP headers - Gives all trhe details required with headers.

Tamper Data -gives header data and also allows to tamper the data.

Tuesday, August 5, 2008

Replacing RMI with Spring Remoting

Custom classes used - Service Interface - - Service Implementation

EXAMPLE_SERVICE_URL - urel (Ex :htpp://10.x.x.x/context/ExampleDetails

context - is the context name under jetty/tomcat where the remote service is running

All other classes are from the spring jar

Service Code(Server)

The bean is instantiated in the service side using the following entry in the spring xml

<bean id="exampleProxy" class=""/>

The implementation is provided to the main applicatuion calling the following url

<bean name="/ExampleDetails" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="exampleProxy"/>
<property name="serviceInterface" value=""/>

The the application can get a reference using the url --> htpp://10.x.x.x/context/ExampleDetails

Main Application Code(client)

The service reference is obtained in the main application by adding the following in the spring xml where
EXAMPLE_SERVICE_URL is htpp://10.x.x.x/context/ExampleDetails obtained from any of the config parameters

<bean id="exampleService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
<property name="serviceUrl" value="${EXAMPLE_SERVICE_URL}"/>
<property name="serviceInterface" value=""/>

Now this service if needed can be used directly in any action or injected into any main service.

<bean id="application" class="com.examples.main.application">
<property name="exampleService" ref="exampleService"/>

Them main advantage of this is a application can speak to any service which is remotely located.

Monday, August 4, 2008

Spring timer tasks for Threads

Create the bean which should be called on regular intervals.

This bean should extend the TimerTask and should have the run method which will be called on timely basis.

<bean id="example" class="">

Make the bean a task and provide the time interval when it needs to be called. The time could be picked from property files.

<bean id="exampleTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="period" value="${exampleTime}">
<property name="timerTask" ref="example">

Add the tasks as part of Timerfactory which will be called based on the time given.

<bean id="timerFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<ref bean="exampleTask">

All the above entries will be part of the spring xml.More then one tasks can be added to the timerfactory

Prototip for easy and Fancy tool Tips

Just came across Prototip which helps to create javascript based tool tips with ease

Could not work more on it as we needed something which supports from IE 5+ versions. Protip supports IE 6+ and Firefox 2+

Running Parallel Db queries on huge Databases.

When the size of the table is very high and the column you are looking for is not indexed then the best way to run the query would be by parallel execution.

This really speeds up the process . But the catch here is that the CPU utilization is high and in production systems this may end up in locks.

This technique can be safely used in backup db servers.


SELECT /*+ parallel(huge_table,4 ) */ * FROM huge_table;

where 4 is the degree of parallelism.The degree of parallelism depends on the capacity of the machines.

Friday, August 1, 2008

Loading multiple property files using Spring

While loading multiple files using spring the following property needs to be added
into bean of the first xml which gets loaded.

< name="ignoreUnresolvablePlaceholders" value="true"/>

Else the subsequent property files will not be loaded.

Some useful unix commands i came across today

vmstat [pamam1] [param2]

shows the server statics along with swap space, cache,io and cpu utilization.

this stats are shown [param2] number of times with [param1] duration in between.


this command also shows the server statistics in detail with
contribution from each process.
This also shows the memory used,cpu utilization and command used for each thread.


Shows the user who are currently logged into the node.

Simplest way to Configure Logging using Log4j

Ensure the log4j.jar & are in the classpath

Add the following into the required classes where logging is needed , so that log shows file name for each logger statement .

private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger([classname].class);

folowed by logger.[info,debug,error,fatal etc]("logger message");

Contents in Log

log4j.rootLogger=ON, ROOT[enabling the root logger]
log4j.appender.ROOT=org.apache.log4j.DailyRollingFileAppender[saving logs on the daily basis with date appended]
log4j.appender.ROOT.File=/a/b/c.log[root log file path]
log4j.appender.ROOT.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss } %-5p [%t] %c{2} - %m%n [pattern for display in each line]

#FILE APPENDER [another logger file ]
log4j.appender.F2.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss } %-5p [%t] %c{2} - %m%n[apache specific errors to be shown on both logger files],F2[for com.example modules debug status messages to be shown in second logger file]

For Log4j debugging
Append -Dlog4j.debug in JAVA_OPTS in which will enable detailed logs in catalina.out showing the logger configerations.

Thursday, July 31, 2008

Apache Basics

Apache Restart

sudo /etc/rc.d/init.d/httpd restart

All requests with port :8080 are caught by tomcat as apache is listening at port 80

requests without ports are heard by apache which listens at port 80 and later redirects through 8009

Directory Structure


conf/ conf.d/ logs/ modules/ run/

httpd.conf ssl.crl ssl.crt ssl.csr ssl.key ssl.prm


authz_ldap.conf jk.conf perl.conf php.conf python.conf README ssl.conf webalizer.conf welcome.conf

1. etc/httpd/conf/httpd.conf

Attributes include
DocumentRoot "/home/partyaccount/website/htdocs"
DirectoryIndex index.jsp index.html inde
DefaultType text/plain
ErrorLog logs/error_log
AddEncoding x-compress Z
ErrorDocument 500 "The server made a boo boo."

2. worker/properties


3. etc/httpd/conf.d/jk.conf

worker assighnments with respective .jsp,.html etc

4. etc/httpd/conf.d/ssl.conf

will have virtual hosts configured here ex:pa112 etc
document root
server admin

Rewrite rules per vhost klike
RewriteEngine on
RewriteRule ^(.*)/.jsp$ $ [L]

Friday, July 25, 2008

Overwriting Struts Resouce Bundle Handling

Care needs to be taken when we overwrite the struts resource bundle handling,especially while overwriting the get text method in struts

This is because , if the customised gettext copies this statment

ResourceBundle bundle = LocalizedTextUtil.findResourceBundle(bundleName, resourceLocale);

where bundlename is the bundle in which property is expected

and if the property does not exist in that bundle, Struts internally looks for the entire set of bundles and searches the key. This is not what is expected
and it consumes a lot of time for each literal check and chokes the server.

A quick fix to this would be to search for the expected bundle and then check if the key which is expected is present.This can be done by using bundle.containskey() and later if it exists then by using the above statement. This reduces a lot of time wasted checking for the entire set of bundle for each property.

Your Kit : A CPU and memory Java Profiler

This is a simple kit with 15 day trial period licence which can be got from

It has both windows and linux versions.For the linux version just copy the

1. copy the into tomcat/bin

2. set the path by typing export LD_LIBRARY_PATH=/tomcat/bin

3. Add -agentlib:yjpagent to Tomcat JVM startup params as

JAVA_OPTS=" -agentlib:yjpagent -server -Xms512m -Xmx768m ......" in

To connect for the same from Windows

1 Install the windos version

2 Click on connect remotely . Enter the ip of the profiling machine

3 This gives most of the stats. For time wise distibution of thread on the running methods

click start profiling.

It also gives snapshots for the required time duration.

Wednesday, July 23, 2008

Adding Logger interceptor in Struts

When i had a requirement to add user name and session id to every logger statement for debugging purposes i did not think it would be so easy. I came across sites which suggested adding some extra modules and configurations into the log4j.

But i realized there was a much simpler way which was to modify the thread name appending application specific user name and session id into it. As anyways log4j will print the thread name at every logger statement . Thus with minimal changes my cause was served. I added this functionality into every request by making it as a interceptor and adding it into the basic stack.
I have attached the interceptor code for reference.

Tasks get easy when seen for different perspectives.

Friday, April 18, 2008

Saturday, January 5, 2008

Struts 2

Apache Struts2 (S2) is an elegant, extensible framework (originally known as WW2) .It has extensible AJAX support ,easy to Spring integration & has POJO Forms & Actions . Deployment is easy , with plugins such as Tiles, Spring, JFreeCharts etc
The requests are received and is executed via the Filter Dispatcher ,The tags allows creating dynamic webapp .It supports style sheet driven markup . It has MVC architecture

The execution flow includes request sent from the user to which the filterDispatcher determines appropriate action . Interceptors are applied and execution of action takes place.
Output rendering and results are shown to the user. Struts2 uses OGNL for expression language .Value Stack plays an important role in retrieving values (hides different scopes from user)

Validation can be performed declaratively in 3 ways .Basic Validation Performed at the server side orClient Validation (or javascript validation) or Ajax Validation

Interceptors are actions sharing common concern or actions validating input or actions involving pre/post processing .Since these Interceptors are shared objects thry should be thread-safe

Tiles is a templating framework for easy creation of web pages with consistent look and feel
Tiles plugin allows to return Tiles pages .It can also be used with freemarker in addition to Jsps

Object Graph Navigation Language (OGNL) is an expression language to get/set properties of java objects .More pervasively being used to map GUI elements to model objects. Tansformations are made easier by OGNL’s TypeConverter mechanism .A more expressive replacement for property-getting language .

Template is a piece of code, usually written in Freemarker, that is rendered by tags . Freemarker is a template engine used to generate output based on a template .It can be used to generate any kind of text: HTML, XML, RTF, Java source code, etc.

Theme is collection of templates packaged together to provide common functionality. qxhtml’ is an example of wrapping the ‘simple’ theme

Free Domain Names @!