Saturday, November 21, 2009

Java Optimizations and other c00l stuff

Java benchmarking
This webpage contains extra material for the Robust Java benchmarking series of articles (Part 1: Issues and Part 2: Statistics and solutions) which were published at IBM developerWorks.

Java Virtual Machine (JVM) - best way to tell when JIT compiling occurs?

An alternative to java String

A rope data structure represents an immutable sequence of characters, much like a Java String. But ropes' highly efficient mutations make ropes — unlike Strings and their mutable StringBuffer and StringBuilder cousins — ideal for applications that do heavy string manipulation, especially in multithreaded environments.

A better API fro managing time and date manipulation in Java


Apache BCEL

Thursday, October 29, 2009

if else in awk

awk 'BEGIN{print max=0}{ if ( 10 > 12 ) print "h"; else print k;} {print $1}' dummy.dum

Tuesday, October 20, 2009

jQuery UI

jQuery UI provides a comprehensive set of core interaction plugins, UI widgets and visual effects that use a jQuery-style, event-driven architecture and a focus on web standards, accessiblity, flexible styling, and user-friendly design. All plugins are tested for compatibility in IE 6.0+, FF 2+, Safari 3.1+, Opera 9.0+, and Google Chrome.


Thursday, October 1, 2009

ssh grep string using spaces causing problems

while running the following command using automated ssh i faced the following issue

ssh pmg-message1 grep -C50 "Oct 1 00:00:00 \(--- \) time taken=3ms, 20013, TEXT, MT" /app/pmg/archived_logs/pmg.log.2.gz

grep: 1: No such file or directory
grep: 00:00:00: No such file or directory
grep: No such file or directory
grep: (---: No such file or directory
grep: ): No such file or directory

This string which i am trying to search is special for two reasons
1) the search string contains special characters ( and ), therefore i used escape sequence.
2) if this query was being run without ssh it is fine but for ss we need to add extra enclosing symbols ' '.as below

ssh pmg-message1 'grep -C50 "Oct 1 00:00:00 \(--- \) time taken=3ms, 20013, TEXT, MT" /app/pmg/archived_logs/pmg.log.2.gz'

Tuesday, September 15, 2009


What is the Mifos Initiative?
Mifos is an industry-wide initiative to address the microfinance industry's information management challenge. Using the open source paradigm, we are creating a new service model that will increase access to technology for all microfinance institutions, ultimately enabling them to extend their reach to the world’s poor.

At the center of the initiative is the Mifos product, a freely available world-class management information system (MIS) that provides the core functionality required by microfinance institutions. The flexibility and scalability of the product means that we'll be able to simultaneously standardize common processes, accommodate regional variations, and scale for new innovations in the future.

We invite you to join with other microfinance institutions (MFIs), IT professionals, software developers, and industry leaders worldwide and become part of the Mifos community. Only with the participation and collaboration of all of us can Mifos have the truly revolutionary impact for which it has the potential.

With Mifos, the microfinance industry as a whole not only benefits from the technology, it contributes to it, improves it, and owns it.

Wednesday, September 9, 2009

Sending Excel file for download from Servlet

Sending Excel file for download from Servlet

In the Tomcat environment you need to add an entry something like this one
to the MIME Type Mappings section of the Tomcat web.xml file. (I don't know
if you can put this in your project's web.xml.)


public static final String CONTENT_TYPE_APP_OCTET_STREAM =
public static final String CONTENT_TYPE_APP_MSEXCEL = "application/
protected void doFileDownload(HttpServletResponse response, String
fileName, String filePath, boolean bFlag) {
try {
File file = new File(filePath + fileName);
String contentType = null;
String headerInfo = null;

if (file.exists()) {
if (type) {
headerInfo = "attachment; filename=\"" + fileName +
} else {
headerInfo = "inline; filename=\"" + fileName + "\"";
} // end if

response.setHeader("Content-Disposition", headerInfo);

// set output stream to the response's output stream
ServletOutputStream servletOut = response.getOutputStream();

// now read file
byte[] dataRead = new byte[(int)file.length()];
FileInputStream fileIn = new FileInputStream(file);

// read in byte data from file and store in byte array, 0, (int)file.length());

// close file
if (fileIn != null) {
} // end if

// write the file to output stream

// flush the output stream
// TODO: handle File Not Found error here
} // end if
catch (Exception ex)
// TODO: handle Exception here

Tuesday, September 1, 2009

Sending Email from java

Code ot Send Email in Java
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

import java.util.Properties;

public class SimpleMail {

private static final String SMTP_HOST_NAME = "";
private static final String SMTP_AUTH_USER = "myusername";
private static final String SMTP_AUTH_PWD = "mypwd";

public static void main(String[] args) throws Exception{
new SimpleMail().test();

public void test() throws Exception{
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");

Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
// uncomment for debugging infos to stdout
// mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setContent("This is a test", "text/plain");
message.setFrom(new InternetAddress(""));
new InternetAddress(""));


private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);

Friday, August 14, 2009


xSocket is an easy to use NIO-based library to build high performance, scalable network applications. It supports writing client-side applications as well as server-side applications in an intuitive way. Issues like low level NIO selector programming, connection pool management, connection timeout detection are encapsulated by xSocket.

With xSocket you are able to write high performance, scalable client and server components such as SMTP Server, proxies or client and server components which are based on a custom protocol.

Wednesday, August 12, 2009

Anonymous inner class code

try {
final Socket conn = socket.accept();
exec.execute(new Runnable() {
public void run() { handleRequest(conn); }

Tuesday, August 11, 2009



Are the Glory Days Long Gone for I.T.?

Are the Glory Days Long Gone for I.T.?

SSH Key One-Liner

If you have to manage a lot of servers or run remote scripts in cron, SSH keys are a lifesaver. It’s so nice to be able to ssh to a machine and instantly log in
without typing a password. Of course, one of the more annoying parts of the process can be setting up the SSH keys on the remote host. Typically, the
process goes something like this:
run ssh-keygen locally,
scp the ~/.ssh/ to the remote server,
then ssh to the remote server and
append that key to your remote ~/.ssh/authorized_keys file.

The above method works, but if you can do the entire thing with a one-liner, why wouldn’t you?
Here’s the SSH one-liner that will copy your local SSH key to the remote host, so you have to type the password only once in the whole process:
$ ssh "cat >> ~/.ssh/authorized_keys" < ~/.ssh/

Friday, August 7, 2009

Thursday, August 6, 2009

Friday, July 31, 2009


What is Kannel?

Kannel is an open source project to make a WAP gateway. Kannel also works as a SMS gateway.


Mockito from Google

Mockito from Google
Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors

Difference between redirect and forward

If a request is forwarded to another request, all name/value pairs stored in the request scope are carried over to the new request. On the other hand, if a request is redirected, the request data are lost.

Another important point to understand about sendRedirect() is that the browser goes to the second resource only after it receives the redirect message from the first resource. In that sense, sendRedirect() is not transparent to the browser. In other words, the servlet sends a message telling the browser to get the resource from elsewhere.

Java Decompiling and Patching

JASPER: Jasper is a program to read Java class files in binary byte code format. The program is capable of generating ASCII files which can be used in conjunction with the Jasmin Assembler. Jasper is also intended to generate input into a class file browser that can produce the inheritance hierarchy and composition maps from the java class files.

Jasper Download

Jasmin is an assembler for the Java Virtual Machine. It takes ASCII descriptions of Java classes, written in a simple assembler-like syntax using the Java Virtual Machine instruction set. It converts them into binary Java class files, suitable for loading by a Java runtime system.

Thursday, July 30, 2009

Get thread stack size at runtime

jinfo -flag ThreadStackSize PID

I found at another forum


Discussion thread

I have an old 2.3 copy of the entire snacc4j tar ball out on sourceforge which should contain the license with it. You can get it hear:

Luckily I had it lying around before IBM totally took this off of opensource.

LDAP programmin Related

The Apache Directory Project

Wednesday, July 29, 2009

Custom Reporting Utilities for Shell

Oracle Coherence
Coherence provides replicated and distributed (partitioned) data management and caching services on top of a reliable, highly scalable peer-to-peer clustering protocol. Coherence has no single points of failure; it automatically and transparently fails over and redistributes its clustered data management services when a server becomes inoperative or is disconnected from the network. When a new server is added, or when a failed server is restarted, it automatically joins the cluster and Coherence fails back services to it, transparently redistributing the cluster load. Coherence includes network-level fault tolerance features and transparent soft re-start capability to enable servers to self-heal.

Sunday, July 19, 2009

Calling EJ from Glassfish Client code

Remember to include


Sunday, July 12, 2009


get it from
Also Read

Tool for code analysis

Thursday, July 9, 2009

Wednesday, July 1, 2009

Monday, June 29, 2009

Limiting number of rows in Database

// mysql
select col from tbl limit 20;

// Oracle
select col from tbl where rownum<=20;

// Microsoft SQL
select top 20 col from tbl;

Sunday, June 21, 2009

Use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup

Using the FindBugs tool
Inefficient use of keySet iterator instead of entrySet iterator

This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup.
if(hashMap != null) {
Set set = hashMap.keySet();
Iterator it = set.iterator();
if (messageId!=null)
string += "MSGID=" + messageId + " ";
string += "TAG Details:{";
while(it.hasNext()) {
Integer intValue = (Integer);
string += GetTagName(intValue.intValue()) + "(" + intValue + ")=" + hashMap.get(intValue);
if (it.hasNext()) string += ", ";

instead use hashMap.entrySet()

Monday, June 15, 2009

Thursday, June 11, 2009

Epoch time Conversion

Epoch Time Conversion
Just in case above website is down
What is epoch time?
The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds. The epoch timestamp 0 can be written in ISO 8601 format as: 1970-01-01T00:00:00Z. One epoch hour is 3600 seconds, one epoch day is 86400 seconds long, leap seconds are not calculated. Many Unix systems store epoch dates as a signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038 problem or Y2038).

Human readable time Seconds
1 minute 60 seconds
1 hour 3600 seconds
1 day 86400 seconds
1 week 604800 seconds
1 month (30.44 days) 2629743 seconds
1 year (365.24 days) 31556926 seconds

How to get the current epoch time in ...
Perl time
PHP time()
Ruby (or To display the epoch:
Python import time first, then time.time()
Java long epoch = System.currentTimeMillis()/1000;
Unix/Linux date +%s
Other OS's Command line: perl -e "print time"

Monday, June 8, 2009


public static String GetStackTraceFromException(Exception e)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);

return sw.toString();

Tuesday, April 28, 2009

Code to connect to a website

Following is the code i used to test an application .
I did not want the thread and also it did not want it to consume CPU.
I wanted it to use random network delay.

try {
long l=System.currentTimeMillis();
URL ourURL = new URL("");
HttpURLConnection huc = (HttpURLConnection)ourURL.openConnection();
huc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
huc.setRequestProperty("Pragma", "no-cache");
BufferedReader reader = new BufferedReader(new

String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("Time taken "+((System.currentTimeMillis()-l)/1000)+"secs");
catch(IOException ioe)
catch(Exception e)
System.err.println("General Exception " + e);

Code taken from here

Wednesday, April 22, 2009

Oracle db connection , Mysql stuff

Oracle jdbc url is
username : system
password: hello


username: hr
password: hr

A very helpfule website
Good Website

Imp links for Mysql setup

Mysql link 1
My Sql link 2

We want MySQL to listen on all interfaces, not just localhost, therefore we edit /etc/mysql/my.cnf and comment out the line bind-address =

Friday, April 10, 2009

Changing forgotten password in Oracle

If you log in as a user with the ORA_DBA group, you will be able to get into your instance without a password. Usually the user on your machine that installed Oracle will work.

Just do this at a command prompt (after setting ORACLE_HOME and ORACLE_SID)

sqlplus "/ as sysdba"

Once you've done that, you can "alter user sys identified by xxxxx" to change the SYS password (replace xxxxx with the new one) .

Faced the problem listener was not starting because it did not have access to the log file for writing.

Exported the following variable at command line
$ LSNR=$ORACLE_HOME/bin/lsnrctl
$ SQLPLUS=$ORACLE_HOME/bin/sqlplus
$ export ORACLE_HOME
$ export PATH=$ORACLE_HOME/bin:$PATH
$ /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/bin/lsnrctl status

TNS:net service name is incorrectly specified
Went to ORACLE_HOME above /network.admin/tnsnames.ora to find out the settings.


user - The login user name defined in the Oracle server.

password - The password for the login user.

host - The host name where Oracle server is running.
Default is - the IP address of localhost.

port - The port number where Oracle is listening for connection.
Default is 1521.

SID - System ID of the Oracle server database instance.
SID is a required value. By default, Oracle Database 10g Express
Edition creates one database instance called XE.

Saturday, April 4, 2009


We must be the change we wish to see

Where you used to be, there is a hole in the world, which I find myself constantly walking around in the daytime, and falling in at night. I miss you like hell. ~Edna St Vincent Millay

What is the opposite of two? A lonely me, a lonely you. ~Richard Wilbur

Your absence has gone through me
Like thread through a needle
Everything I do is stitched with its color.
~W.S. Merwin, "Separation"

Why can't we get all the people together in the world that we really like and then just stay together? I guess that wouldn't work. Someone would leave. Someone always leaves. Then we would have to say good-bye. I hate good-byes. I know what I need. I need more hellos. ~Charles M. Schulz

God is closest to those with broken hearts. ~Jewish Saying

If you're going through hell, keep going. ~Winston Churchill

The robbed that smiles, steals something from the thief. ~William Shakespeare, Othello

Wednesday, April 1, 2009

Awk Commands to remember

following example prints the second field of each input record whose first field is precisely
$ awk '$1 == "foo" { print $2 }' filename

following regular expression match accepts any record with a first field that contains ‘foo’:
$ awk '$1 ~ /foo/ { print $2 }' filename

A regexp constant as a pattern is also a special case of an expression pattern. The
expression /foo/ has the value one if ‘foo’ appears in the current input record. Thus, as a
pattern, /foo/ matches any record containing ‘foo’.

Boolean expressions are also commonly used as patterns. Whether the pattern matches
an input record depends on whether its subexpressions match. For example, the following
command prints all the records in ‘BBS-list’ that contain both ‘2400’ and ‘foo’:
$ awk '/2400/ && /foo/' BBS-list

The following command prints all records in ‘BBS-list’ that contain either ‘2400’ or
‘foo’ (or both, of course):
$ awk '/2400/ || /foo/' BBS-list

The following command prints all records in ‘BBS-list’ that do not contain the string
$ awk ’! /foo/’ BBS-list

Good Website for Awk One liners

Wednesday, March 25, 2009

Monday, March 23, 2009

Reading and Writing a Properties File

// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream(""));
} catch (IOException e) {

// Write properties file.
try { FileOutputStream(""), null);
} catch (IOException e) {

Here is an example of the contents of a properties file:

# a comment
! a comment

a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e.f = another string

Taken from here

Thursday, March 19, 2009

Findings Logs between two time intervals

awk '{ if ($3>="16:30:00" && $3<="16:42:00"){print $0}}'filename.log

Scenes from Recession

Recession in Photos

Zipping and Unzipping Files in UNIX

Zipping and Unzipping Files in UNIX

There are several methods of archiving files and retrieving archives. We recommend using the "zip" function to compress your files for its ease of use and portability. (Files zipped in Unix can be extracted using WinZip or PKunzip in Windows). We have provided various "unzip" methods. The "right" unzip method depends upon the method used to zip the file. You can tell the zip method by the file extension (e.g., .zip, .tar, .gz, etc.)

Zipping Files Using ZIP

This Unix program is compatible with the zip program for DOS and Windows. To zip files, first have the files uploaded to your server, then log into your account with Telnet. Navigate to the directory where the files are that you want to zip (for instance by typing cd www then cd sounds to move to your /www/sounds directory). Then type:

zip myzip file1 file2 file3

This puts the files named file1, file2, and file3 into a new zip archive called

Unzipping Files

Please note that the unzip method you use is defined by the filename you are trying to unzip. For example, if you are trying to unzip a file called file.tar - you would use the method described in "tar". Files ending in .gzip or .gz need to be extracted with the method described in "gunzip".


If you have an archive named and want to get back the files, you would type:


Typing zip or unzip by itself will give you a usage summary, showing nearly all the options available.


To extract a file compressed with tar (e.g., filename.tar), type the following command from your telnet prompt:

tar xvf filename.tar

Basically, this command means that you will see the file "explode", so don't worry when you see your screen scrolling wildly. It also means that you will see any errors in the archive.


To extract a file compressed with gunzip, type the following:

gunzip filename_tar.gz

then if you receive no errors, type:

tar xvf filename_tar

Taken From here

Friday, February 27, 2009

The rev command

rev command is used to print the lines of a file in reverse order.
i used it with cut to cut the last column of a file . I used it
because a column in the begining used special character in it

for eg:
Irregular line
"Buongiorno","BUSA, Inc",11222,"ALT",2325,22318.75
regular line
the comma after BUSA gives wrong column

awk command to sum a column

bbs-list file

aardvark 555-5553 1200/300 B
alpo-net 555-3412 2400/1200/300 A
barfly 555-7685 1200/300 A
bites 555-1675 2400/1200/300 A
camelot 555-0542 300 C
core 555-2912 1200/300 C
fooey 555-1234 2400/1200/300 B
foot 555-6699 1200/300 B
macfoo 555-6480 1200/300 A
sdace 555-3430 2400/1200/300 A
sabafoo 555-2127 1200/300 C

awk command for sum of a column

cat bbs-list | cut -f3 -d" "|cut -f1 -d"/"| awk '{ s=$0+s} END {print s}'


awk -F: ’{ print $1 }’ /etc/passwd | sort

Monday, February 23, 2009

Print the Stack Trace of the Exception to a String

When an exception occurs, this code snippet will print the stack trace of the exception to a string. This way, the exception stack trace at runtime can be recorded in log file.

public static String getStackTrace(Throwable t)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
return sw.toString();
Taken from Devx
Sujata De

Friday, February 13, 2009

Linux / Unix / Solaris date command

Using perl Command line
ls -1 | perl -n -e 'chop; print localtime( (stat($_))[9] ) . "\n";

The perl command processes each line of input (with -n option) and for each line, $_ is the input line. "chop" removes the newline character at the end of the line. "stat" retrieves the inode data from the filename (in $_). "localtime" will spit out the date/time of the file using the local timezone. (Use "gmtime" if you want it to ignore timezone settings.)

Log style date command
date '+ %b %e %T'


echo `date +"%Y-%m-%d"`




echo `date +"%Y-%m-%d_%H-%M-%S"`



You can use these for creating files names of backups.

Taken from following linkdate command
Another good date link

Friday, January 30, 2009

Seraching for exception in log file

for X in $(egrep -o "[A-Z]\w*Exception" log_week.txt | sort | uniq) ;
echo -n -e "processing $X\t"
grep -c "$X" log_week.txt

From the productive programmer

Saturday, January 10, 2009

After Ubuntu Kernal Related Upgarde Vbox Issue

Issue the following commands

sudo aptitude install virtualbox-ose virtualbox-ose-source module-assistant
sudo m-a prepare
sudo m-a a-i virtualbox-ose

to rid of vbox startup issues after Kernel Upgrade in Ubuntu.

Thursday, January 1, 2009

Installing new modules in Perl

One might want to perform various operations using Perl such as database operations, LDAP queries. To install various modules

The the information is contained on the following page
Adding Perl Modules

Controlling Eclipse Memory options

Either add the following to eclipse.ini or to the launcher that launches eclipse

eclipse -Xms=512m -Xmx=1024m

Setting the limits in Linux permanently app soft nofile   16384 * hard...