Tuesday, August 31, 2010

Comparison of different SQL implementations


Most of the time when we port application from one database to other we look for equivalent command in other database. Here is a site that provides a comprehensive list of different sql implementations. more info at http://troels.arvin.dk/db/rdbms/

Wednesday, June 30, 2010

எளிமையாய் சொன்னேன்


என் பிறந்தநாள் வாழ்த்தே
முதன்முதலாய் இருக்க
முந்தியநாள் நள்ளிரவே
வாழ்த்து சொல்லியிருக்கிறேன்
தொலைபேசியில்...

உன் விழிகள் என்னையே
முதன்முதலாய் சந்திக்க
அதிகாலை ஐந்து மணிக்கே
உன் விடுதி வாயிலில் நின்றிருக்கிறேன்
வாழ்த்து அட்டைகளுடன்...

உன் பிறந்தநாளின்
முதல் மின்னஞ்சல்
என் கவிதையாய் இருக்க
மென்பொருளொன்று செய்திருக்கிறேன்
ஆயிரம் கவிதைகளுடன்...

இதுவரை இப்படித்தான்
உன்னை ஆச்சரியமூட்டியிருகிறேன்
என் வாழ்த்துகளால்...

இன்று உன் பிறந்தநாள்
இது என் மனைவியாக
உனக்கு முதல் பிறந்தநாள்...

எப்படி சொல்வது
என் வாழ்த்துகளை
இதுவரை இல்லாத வகையில்?
என்று எண்ணி எண்ணி
ஏதும் கிடைக்காமல்
எளிமையாய் சொன்னேன்
"இனிய பிறந்தநாள் வாழ்த்துக்கள்..."

வாழ்த்துக்களுடன்
விஜயன் சீனிவாசன்

Thursday, April 15, 2010

Check what all ports running

If you know the port at which that service runs then issue the following command
[vijayan@boarddown-dr ~]$ netstat -an | grep LISTEN | grep 80
tcp 0 0 0.0.0.0:807 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:5801 0.0.0.0:* LISTEN
tcp 0 0 :::80 :::* LISTEN

To know which process id owns this port
[vijayan@boarddown-dr ~]$ sudo /sbin/fuser 80/tcp
80/tcp: 25529 25530 25531 25532 25533 25534 28522

To know which executable/script runs on that process id
[vijayan@boarddown-dr ~]$ ps -lfwwwwwp 25529
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
5 S root 25529 1 0 75 0 - 953 - Feb17 ? 00:00:00 /home/vijayan/dev/Apache2/bin/httpd -k start

Thursday, February 04, 2010

Get Password without displaying it on console

JDK 1.6 provides option to get secret inputs without displaying them on console. Here is the code sample to do that.



System.console().readPassword("[%s]", "Password:");

Tuesday, February 02, 2010

Online Free Flex based Building Plan Software

If anyone of you thinking to build a new home and looking for a software that can help you model your home. Here is the link you can use this for free.
http://dragonfly.autodesk.com/

Thursday, January 28, 2010

Specifying default schema name in JPA

Often we use different user name to connect to oracle database instead of the using the same user name with schema name. In that case queries needs to be prefixed with schema names. to do that in JPA we can add the following property in persistence.xml file




com.foo.bar.Test




Tuesday, January 19, 2010

Access Oracle Blob and Timestamp Columns

Many of the time we use Blob and Timestamps column in Oracle. When we access them using JDBC, we will get Oracle specific Java objects when result set is returned from DB. e.g oracle.sql.BLOB, oracle.sql.TIMESTAMP but we may need them in the form of java.sql.Blob and java.sql.Timestamp

To get it in right way we need add the following start-up properties

-Doracle.jdbc.J2EE13Compliant=true

Saturday, October 03, 2009

Ways by which singleton can be created

Singleton classes can be created in 3 ways

Case 1:

package org.vijayan.sample;

public class Singleton {

/**
* Advanced Initialization
*/
public static final Singleton SINGLETON=new Singleton();
private Singleton(){
}

public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.SINGLETON);
}
}
}


In this case the statically created object is made final and publicly exposed to everyone.

Case 2:


package org.vijayan.sample;

public class Singleton {

/**
* Advanced Initialization
*/
private static Singleton singleton=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}


Case 3:


package org.vijayan.sample;

public class Singleton {

/**
* Lazy Initialization
*/
private static Singleton singleton=null;
private Singleton(){
}

public static Singleton getInstance(){
if(singleton==null){
singleton=new Singleton();
}
return singleton;
}

public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}


In this third case is preferable because it creates the object on-demand. But it can create issue when it is used in multi threaded environment.

So the code can be changed to case 4

Case 4:


package org.vijayan.sample;

public class Singleton {

/**
* Lazy Initialization
*/
private static Singleton singleton=null;
private Singleton(){
}
/**
*
* Will take care multi threaded environment but it expensive
*/
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton=new Singleton();
}
return singleton;
}
public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}
}


Though it takes care multi threaded this will become a costly method. to make it a light-weight we can change the code to case 5

Case 5:


package org.vijayan.sample;

public class Singleton {

/**
* Lazy Initialization
*/
private static Singleton singleton=null;
private Singleton(){
}
/**
*
* Will take care multithreaded environment also less expensive
*/
public static Singleton getInstance(){
if(singleton==null){
synchronized (Singleton.class) {
if(singleton==null){
singleton=new Singleton();
}
}
}
return singleton;
}

public static void main(String[] args) {
for(int i=0;i<4;i++){
System.out.println(Singleton.getInstance());
}
}

}


This method is an efficient but complex one, this is also called as double-null checking method. more info on this can be found in http://en.wikipedia.org/wiki/Double-checked_locking

Output:

org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9
org.vijayan.sample.Singleton@10b62c9

Please note all 4 times it returns the same object reference.

Synchronization usecases

Consider a class called A, it has m1() and m2() methods, 2 instance of this A class is created a1 and a2 and there are 2 threads t1, t2

Case 1: m1() and m2() are not synchronized

t1 uses a1 and calls m1()

t2 uses a2 and calls m2()

both thread t1 and t2 can run at the same time because both threads are using different objects.

Case 2: m1() and m2() are synchronized

t1 uses a1 and calls m1()

t2 uses a2 and calls m2()

both thread t1 and t2 can run at the same time because both threads are using different objects.
by default synchronization will acquire lock on the object, since here both are using different object locking will not happen.

Case 3: m1() and m2() are synchronized

t1 uses a1 and calls m1()

t2 uses a1 and calls m2()

both thread t1 and t2 cannot run at the same time because both threads are using same object.
if t1 first access m1() then t2 will have to wait for t1 to complete running m1()

Case 4: m1() is static and m2() is non static and both are synchronized

t1 uses a1 and calls m1()

t2 uses a1 and calls m2()

both thread t1 and t2 can run at the same time because though both threads are using same object when t1 first access m1() it is not accessing via a1 object rather it will use A class for accessing the static method that is A.m1() is what called. For doing the same A.Class object will be created and it will be synchronized using A.Class object and t2 will be using a1 object for locking since both objects are different they can work parallel.

Case 5: m1() is static and m2() is static and both are synchronized

t1 uses a1 and calls m1()

t2 uses a1 and calls m2()

both thread t1 and t2 cannot run at the same time because though both threads are using same object (A.Class object)

Why synchronization in java?

Consider the following programs

package org.vijayan.sample;

public class Main {

public static void main(String[] args) {
SampleFile file=new SampleFile("test.txt");
FileWriterThread mt1=new FileWriterThread(10000,"MT1", file);
FileWriterThread mt2=new FileWriterThread(20,"MT2", file);
mt1.start();
mt2.start();
}

}

package org.vijayan.sample;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class SampleFile {

private File file;
public SampleFile(String fileName){
file=new File(fileName);
file.delete();
}
public void writeMessage(int count, String message){
try {
FileWriter writer=new FileWriter(file,true);
for(int i=0;i
writer.write(message+"-"+i);
writer.write("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

package org.vijayan.sample;

public class FileWriterThread extends Thread {

private SampleFile file;
private int count;
public FileWriterThread(int count, String name, SampleFile math){
super(name);
this.file=math;
this.count=count;
}
@Override
public void run() {
file.writeMessage(count, getName());
}
}

Output of the above program can result

MT1-1026
MT1-1027
MT1-1028
MT1-1029
MT1-1030
MT1-1031
MT1-1032
MT1-1MT2-0
MT2-1
MT2-2
MT2-3
MT2-4
MT2-5
MT2-6
MT2-7
MT2-8
MT2-9
MT2-10
MT2-11
MT2-12
MT2-13
MT2-14
MT2-15
MT2-16
MT2-17
MT2-18
MT2-19
033
MT1-1034
MT1-1035
MT1-1036
MT1-1037

Please note the bold lines carefully. In this case both thread is using same SampleFile Object and both thread is writing to a same file concurrently. Since there is no synchronized keyword for writeMessae() it is possible. if we make this method synchronized like below

public synchronized void writeMessage(int count, String message){
try {
FileWriter writer=new FileWriter(file,true);
for(int i=0;i
writer.write(message+"-"+i);
writer.write("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

then the output will change to like the following

MT1-9994
MT1-9995
MT1-9996
MT1-9997
MT1-9998
MT1-9999
MT2-0
MT2-1
MT2-2
MT2-3
MT2-4
MT2-5
MT2-6
MT2-7
MT2-8
MT2-9
MT2-10
MT2-11
MT2-12
MT2-13

Output 2 indicates that though both thread is started running the second thread is waiting until first thread completes its operation. though it is providing desired output we may not want to make the second thread wait until full completion of thread 1. This can be achieved by changing the program to following ways.


package org.vijayan.sample;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class SampleFile {

private FileWriter writer;
public SampleFile(String fileName){
File file=new File(fileName);
file.delete();
try {
writer=new FileWriter(file,true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
writer.close();
}
public void writeMessage(int count, String message){
try {
for(int i=0;i
synchronized (writer) {
writer.write(message+"-"+i);
writer.write("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:

MT1-1218
MT1-1219
MT2-0
MT2-1
MT2-2
MT2-3
MT2-4
MT2-5
MT2-6
MT2-7
MT2-8

Please note adding a synchronized block requires some extra code and it always needs to be done carefully.

Monday, September 14, 2009

equals(), hashCode() and toString() methods in Object


//hashCode in Object class

public native int hashCode();

//Java doc for hashCode()

int java.lang.Object.hashCode()


Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

The general contract of hashCode is:

* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
* If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
* It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

//equals() method in Object class
public boolean equals(Object obj) {
return (this == obj);
}


package object;

public class User {

private String firstName;
private String lastName;
private Integer mark;
public User(String firstName,String lastName, Integer mark){
setFirstName(firstName);
setLastName(lastName);
setMark(mark);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getMark() {
return mark;
}
public Integer setMark(Integer mark) {
this.mark = mark;
}
}


package object;

public class ObjectTest {

public static void main(String[] args) {
User user1=new User("Vijayan", "Srinivasan", new Integer(100));
User user2=new User("Vijayan", "Srinivasan", new Integer(100));
System.out.println("[user1==user2]="+(user1==user2));
System.out.println("[user1.equals(user2)]="+user1.equals(user2));
}
}


So both case it is giving false becasue, both of the statements uses the same logic to compare 2 objects. For getting this right we have to do the following.

//Override equals() method in User class

public boolean equals(Object object) {
if(object instanceof User){
User user=(User) object;
return
equals(firstName,user.firstName) &&
equals(lastName,user.lastName) &&
equals(mark,user.mark);
}
return false;
}

// Implementation of toString() in Object class
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}


Although it is sufficient that overriding equals methods alone sufficient here it is adviced to override also for better performance. //Why?


// implementation of put() method in Hashtable class

public Object put(Object key, Object value) {
// Make sure the value is not null
if (value == null) throw new NullPointerException();

// Makes sure the key is not already in the hashtable.
HashtableEntry e;
HashtableEntry tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;

for (e = tab[index] ; e != null ; e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) { //<------ Look here
Object old = e.value;
e.value = value;
return old;
}
}


Please note if we have proper hashCode() impelentation there is no need of calling the equals() method at all. Hence if the object is different we can let the Hashtable know ahead of calling equals() method. That is the reason it is always important to implement hashCode() when ever we override the equals()

Wednesday, September 09, 2009

Seting gnome on Linux VNC server

In redhat linux, when we start VNC server, by default it used to start with a simple termial based view. Inorder to start it as gnome based session the following command can be used

  1. Set the vnc session as gnome
    > vi ~/.vnc/xstartup (remove all the lines and add only the following lines)
    unset SESSION_MANAGER
    vncconfig -iconic &
    gnome-session &
  2. Start VNC server
  3. > vncserver - geometry 1024x768
Use the correct ip address and X-display id to connect to the VNC e.g. 10.66.92.127:1

Monday, September 07, 2009

Visio type tool on SAAS

Most of would have used Microsoft Visio for creating various diagrams such as Class, Network, Flowchart etc., Here is a tool that does everything online ( http://creately.com/ ). This tool has developed in Flex also allows us to save and collaborate among team members.

Thursday, August 20, 2009

Jboss JDBC Driver Loading Issue

If we configure data source throug *-ds.xml (e.g. mysql-ds.xml) file in Jboss and the corresponding JDBC driver jar is only available in a WEB-INF/lib folder of an application, even though the same application tries to get a connection through configured data source, first time it will throw an ClassNotFoundException. As the class would not have loaded until the first call.

But if we try to get connection second time it will work with out any exception. This problem can be rectifed by keeping the copy of the JDBC driver jar in /server//lib folder (e.g. c:\jboss 4.0.2 \server\default\lib). This will ensure that the driver jar will be loaded in to ClassLoader at the time of server starting.

Monday, August 17, 2009

Incorrect arguments to mysql_stmt_execute

When we use MySQL connector mysql-connector-java-5.0.4-bin.jar with PreparedStatement contains more number of columns we may get the following Exception
java.sql.SQLException: Incorrect arguments to mysql_stmt_execute
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)

To fix this issue we have to use mysql-connector-java-5.1.8-bin.jar

Tuesday, June 30, 2009

Observer and Observable Example

In Java we have Observer interface and Observable class, Below program gives a sample use of Observer and Observable

import java.util.Observable;

public class Employee extends Observable {
float salary;

public void setSalary(float newSalary) {
salary = newSalary; // salary has changed
setChanged(); // mark that this object has changed, MANDATORY
notifyObservers(new Float(salary)); // notify all observers, MANDATORY
}
}

import java.util.Observable;
import java.util.Observer;

public class Manager implements Observer {

public void update(Observable obj, Object arg) {
System.out.println("A change has happened and new salary is " + arg);
}
}


public class Demo {
public static void main(String[] args) {
Employee e = new Employee();
Manager m = new Manager();
e.addObserver(m); // register for observing
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
if (i == 5) {
e.setSalary(100);
}
}
}
}

அழகாக தெரிகிறது தமிழ்...

உனக்கு வாழ்த்து
எழுதும்போது மட்டும்
அத்தனை அழகாக
தெரிகிறது தமிழ்...

உன் பெயரை
உச்சரிக்கும்போது மட்டும்
சுகமாக ஒலிக்கிறது
என் குரல்...

என்னோடு நீ
இருக்கும்போது மட்டும்
சொர்க்கமாக தெரிகிறது
இந்த உலகம்...

என்னோடு நீ
நடக்கும்போது மட்டும்
சிறியதாக குறைகிறது
சாலையின் நீளம்...

மொத்தத்தில் உனக்காக
இந்த வாழ்த்து மடல்
எழுதுவதில் என் மனம்
சந்தோசத்தில் நிறைகிறது...

இனிய பிறந்தநாள்
வாழ்த்துக்கள்!!!

விஜயன் சீனிவாசன்

Monday, June 29, 2009

Reading CSV Files Using csvjava 2.0

Recently I have gone through a new CSV Reader called csvjava 2.0 It is a very simple tool which has only 2 classes CSVReader and CSVWritter but yet very powerful. Below I have wrote one sample program using CSVReader class of csvjava 2.0.

This CSV Reader supports all escapping that has been supported by CSV file format.

e.g.
Hi Vijayan This is a Test,"""Simple Test with , and """,A,B,CV
Will be treated as follows
Column 1: Hi Vijayan This is a Test
Column 2: "Simple Test with , and ""
Column 3: A
Column 4: B
Column 5: CV

import java.io.FileNotFoundException;
import java.io.IOException;

import com.csvreader.CsvReader;


public class CSVReaderSample {

public static void main(String[] args) {
try {
CsvReader reader=new CsvReader("Vijayan.csv");

while(reader.readRecord()){
System.out.print(reader.getCurrentRecord()+")");
System.out.print(reader.get(0));
System.out.print("\t");
System.out.print(reader.get(1));
System.out.print("\t");
System.out.print(reader.get(2));
System.out.print("\t");
System.out.print(reader.get(3));
System.out.print("\t");
System.out.println(reader.get(4));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Friday, June 26, 2009

Java FTP Sample Code

Writing FTP Code using ANT is very simple compare to we write the same using FTPClient class. This post will explain you how to do basic FTP operation through ANT FTP task classes.

import java.io.File;

import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.optional.net.FTP;
import org.apache.tools.ant.types.FileSet;

public class FtpUsingAnt {

public static void main(String[] args) {
ftpGetSample();
ftpDeleteTaskSample();
}


public static void ftpGetSample(){
FTP ftp=new FTP();
FTP.Action action=new FTP.Action();
action.setValue("get");
ftp.setAction(action);
ftp.setServer("server.com");
ftp.setUserid("user-name");
ftp.setPassword("password");
ftp.setRemotedir("/remote-folder");
FileSet fileSet=new FileSet();
File dir=new File("c:\\local-folder");
fileSet.setDir(dir);
fileSet.setIncludes("**/*.csv");
ftp.addFileset(fileSet);
callAntTask(ftp, "ftp");
}


public static void ftpDeleteTaskSample() {
FTP ftp=new FTP();
FTP.Action action=new FTP.Action();
action.setValue("del");
ftp.setAction(action);
ftp.setServer("server.com");
ftp.setUserid("user-name");
ftp.setPassword("password");
ftp.setRemotedir("/remote-folder");
FileSet fileSet=new FileSet();
File dir=new File("."); // Not Needed
fileSet.setDir(dir);
fileSet.setIncludes("**/*.csv");
ftp.addFileset(fileSet);
callAntTask(ftp, "ftp");
}


public static void callAntTask(Task task, String taskName){
DefaultLogger logger=new DefaultLogger();
logger.setMessageOutputLevel(Project.MSG_DEBUG);
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);

Project project=new Project();
project.addBuildListener(logger);
task.setProject(project);
task.setTaskName(taskName);
task.execute();
}

}

Monday, June 22, 2009

How Class.forName() registers driver?

Most of the time for registering driver to DriverManager, we use the following code.

Class.forName("com.mysql.jdbc.Driver");

But Class.forName() method will not do any registration of Driver with DriverManager. If that is the case how DriverManager.registerDriver() (registration) is called?

static {

try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (java.sql.SQLException E) {
throw new RuntimeException("Can't register driver!");
}

}

This is snippet is taken from com.mysql.jdbc.Driver class's source code. So if you closely watch this code, when ever
 Class.forName("com.mysql.jdbc.Driver");
is invoked as soon as the class is loaded in to the memory, all static blocks of that classes are also being invoked. Insite one of the static block all driver classes are registering them self to DriverManager.