Wednesday, October 14, 2009

Varargs in Java

What is varargs ?

varargs - Variable arguments supported in Java from JDK1.5 and higher.
For example you want to specify variable argument in constructor or method you can do it in following ways:

1) Constructor:
public Employee(String firstName, String lastName, String... address);
Note String... is vairable argument.

2) Method:
public int maximum(int first, int... rest);
So variable argument can be of any type.

How JVM interprets ?

When you specify a variable-length argument list, the Java compiler
essentially reads that as “create an array of type ”.
So if you typed:

public Employee(String firstName, String lastName, String... address);

However, the compiler interprets this as:

public Employee(String firstName, String lastName, String[] address);

How to read varargs?

So you can read it as a array directly.
public int maximum(int first, int... rest) {
int max = first;
for (int i : rest) {
if (i > max)
max = i;
}
return max;
}

How to call Varargs method:

If the method is:
public int maximum(int first, int... rest);

It can be called in following ways:
int max = maximum(9, 4);
int max = maximum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int max = maximum(18, 8, 78, 29, 19889, -908);

Classic example of varargs is System.out.printf(String... String);

Varargs Limitations:

1) There can be only one varargs as parameter.
2) varargs should be the last parameter in the list.

Thursday, August 27, 2009

Distributed Transaction in Java

What is Distributed Transaction ?

Transaction that access and update two or more resources across network.
Example: Different database(s) (MySQL, Oracle, Sybase etc) located on single server or single instance of the database(s) located on different servers (Server1, Server2 ...) or combination of above.


How we can achieve distributed transaction in java ?

We can achieve distributed transaction using the XA datasource and JTA.

Important Interfaces:

There are three important interfaces:

1) UserTransaction - (javax.transaction.UserTransaction)
It provides application the ability to controls the trasaction boundary programatically. It starts the global transaction and associates that transaction to the calling thread.

2) Transaction Manager - (javax.transaction.TransactionManager)
This interface allows application server to controls the transaction boundary on behalf of application being managed. Transaction manager is responsible whether to commit or rollback any distributed transaction.

3) XAResource— (javax.transaction.xa.XAResource)
Is a Java mapping of the industry standard XA interface.

Note: JDBC driver should support XAResource portion of JTA.

How distributed transaction works?

Application send request to transaction manager to start the transaction via usertransaction object. Once the transaction is started it will associate itself to the current thread.

After that application can access different datasources belonging to different databases or same databases located on single or multiple servers.

Transaction manager treat the whole unit as one single logical unit irrespective of different database and will commit in case of sucess or rollback if any exception/s.

Implementation:

We implement in JBOSS and Tomcat Servers using mysql as database server.

Use Case:

User will enter id and name which will be stored into two different mysql databases. Table structure will be same in both database except one database will have primary key configured, so when user enters duplicate value it will throw sql exception.

SQL Script:

Database: DB1
CREATE TABLE `xadb`.`EmpTest` (
`id` int NOT NULL,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE = InnoDB;

Database: DB2
CREATE TABLE `EmpTest` (
`id` int NOT NULL,
`name` varchar(50) NOT NULL

)
ENGINE = InnoDB;

Directory Structure of war file:

xadir
|------ input.jsp
|------ bl.jsp
|------ WEB-INF (Folder)
|---- web.xml
|---- lib (Folder)
|---- classes (Folder)
|---- foo (Folder)
|--- XATest.java

JSP Code:

input.jsp



bl.jsp



Java Code:
package foo;

import java.sql.PreparedStatement;
import java.sql.Connection;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

public class XATest{


public String insertData(int id, String name) {
UserTransaction ut = null;
String returnStr = null;
Connection conn1 = null;
Connection conn2 = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {

//Creating the context
Context ctx = new InitialContext();
//Getting datasource
DataSource ds1 = (DataSource)ctx.lookup("java:ds1");
DataSource ds2 = (DataSource)ctx.lookup("java:ds2");
//Getting the user transaction
ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");
//Starting the transaction
ut.begin();
printStr("Transaction Started .....................");
//Processing First Database
conn1 = ds1.getConnection();
pstmt1 = conn1.prepareStatement("insert into EmpTest values ( ?,?)");
pstmt1.setInt(1, id);
pstmt1.setString(2, name);
int exeVal = pstmt1.executeUpdate();
printStr("Statement Executed: "+exeVal);

//Processing Second Database
conn2 = ds2.getConnection();
pstmt2 = conn2.prepareStatement("insert into EmpTest values ( ?,?)");
pstmt2.setInt(1, id);
pstmt2.setString(2, name);
exeVal = pstmt2.executeUpdate();
printStr("Statement Executed: "+exeVal);

printStr("Committing the transaction ...... ");
ut.commit();
pstmt1.close();
pstmt2.close();
conn1.close();
conn2.close();
returnStr = "Transaction Successful";
}catch(Exception e) {

returnStr = "Transaction Failed";
e.printStackTrace();
try {
ut.rollback();
} catch (IllegalStateException ex) {
ex.printStackTrace();
} catch (SecurityException ex) {
ex.printStackTrace();
} catch (SystemException ex) {
ex.printStackTrace();
}

} finally {
try {
pstmt1.close();
pstmt2.close();
conn1.close();
conn2.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
return returnStr;
}

private void printStr(String s) {

System.out.println(s);
}
}
)


Implementing in JBOSS (jboss-4.2.2):
1) create the file mysql-xa-ds.xml under jboss_home/server/default/deploy folder.

2) Add the driver jar file (mysql-connector-java-5.0.8-bin.jar) in
jboss_home/server/default/lib folder.

3) Add the following to the file created in step-1


Note: When the JBOSS start make sure that JNDI are created properly.


4) create the war file and deploy the same in JBOSS.

5) Enter the test data.

a) Id= 1 Name = Milind
Result --
Trasaction Sucessful
b) Id= 2 Name = Guest
Result --
Trasaction Sucessful
c) Id= 1 Name = Guest1
Result --
Trasaction Failed Reason -- Primary Key violation.
Check the table in DB1 and DB2 database both should not have record of 1,Guest1





Wednesday, April 15, 2009

How to start existing windows xp from Ubuntu

How to start existing windows xp from Ubuntu

Step-1 Install Virtual Box

Open terminal (Alt-F2 Type terminal) and type

mkdir ~/virtualbox

cd ~/virtualbox

wget -c http://download.virtualbox.org/virtualbox/2.1.4/virtualbox-2.1_2.1.4-42893_Ubuntu_hardy_i386.deb

ls -ltr

You should able to see file virtualbox-2.1_2.1.4-42893_Ubuntu_hardy_i386.deb

If file is found with virtualbox-2.1_2.1.4-42893_Ubuntu_hardy_i386.deb?xxxxxx then type following command

mv virtualbox-2.1_2.1.4-42893_Ubuntu_hardy_i386.deb?xxxxxx virtualbox-2.1_2.1.4-42893_Ubuntu_hardy_i386.deb

dpkg -i virtualbox-2.1_2.1.4-42893_Ubuntu_hardy_i386.deb

Note: If following libraries are not found/compitable you need to download and install following files

libqt4-core_4.3.4-0ubuntu3_i386.deb
URL: http://packages.ubuntu.com/hardy/libqt4-core
libqt4-gui_4.3.4-0ubuntu3_i386.deb
URL : http://packages.ubuntu.com/hardy/i386/libqt4-gui/download
libaudio2_1.9.1-1_i386.deb
URL: http://packages.ubuntu.com/hardy/libaudio2

to install use the command
dpkg -i *.deb

Once it is done you should able to start the virtual box.

Open terminal (Alt-F2 Type terminal) and type
VirtualBox

alternative you can use menu Applications > System Tools > Virtual Box

Step - 2 Creating Master Boot Record

Type following in terminal

install-mbr --force myBootRecord.mbr

Step 3 Getting the partition details where window is installed

Type following in terminal

sudo fdisk -l /dev/sda

It will display
Device Boot Start End Blocks Id System
/dev/sda1 * 1 6374 51199123+ 7 HPFS/NTFS
/dev/sda2 6375 9729 26949037+ 5 Extended
/dev/sda5 6375 9585 25792326 83 Linux
/dev/sda6 9586 9729 1156648+ 82 Linux swap / Solaris

Step 4 Creating group permission

Type following in terminal

sudo usermod -a -G disk user_name

Log Out and Login again.

Step 5 Creating Virtual Disk and registering the same

VBoxManage internalcommands createrawvmdk -filename ./WinXP.vmdk -rawdisk /dev/sda -partitions 1 -mbr ./myBootRecord.mbr -relative -register

Note:
Change the following in above command:
-rawdisk /dev/sda to -rawdisk your_device
-partitions 1 to -partitions your_partion Number.

Step 6 Configuring Virtual Box

Open Virtual Box ( Refer Step 1)

Click Setting > General > Advance

Check all extended features.

Step 7 Finally Creating New Virtual Machine

Open Virtual Box ( Refer Step 1)

Click New -- Virtual Machine Wizard will come

Click Next

Enter your desire name

Select Operating System : Microsoft Windows
Version: Window XP
Click Next

Select Base Memory Size : 512 MB

Click Next

Click exsisting

Click Add

Browse your WinXP.vmdk file created in step 5

Click Finish

Your Virtual Box is ready select it and press start it will start your windows in Ubuntu

Note: To enter cltr+alt+delete use HOST (right control key) + Del










Permanently Mounting Windows Partition on Linux - Ubuntu/Linux

Permanently Mounting Windows Partition on ubuntu/Linux:

1) Create the folder where you want to mount the partition
sudo mkdir -p /media/disk

2) Find the disk to mount
sudo fdisk -l
Output would be like this:
Device Boot Start End Blocks Id System
/dev/sda1 * 1 6374 51199123+ 7 HPFS/NTFS
/dev/sda2 6375 9729 26949037+ 5 Extended
/dev/sda5 6375 9585 25792326 83 Linux
/dev/sda6 9586 9729 1156648+ 82 Linux swap / Solaris

In our case it is /dev/sda1
3) Open the /etc/fstab
sudo gedit /etc/fstab &

4) Copy the following line at the end in /etc/fstab
#Window Drive
/dev/sda1 /media/disk ntfs rw,nosuid,nodev,noatime,allow_other,blksize=4096 0 0

5) Save the file.

6) So when you restart windows partition will be mounted on /media/disk

7) To check mounted or not go to the /media/disk directory or open the file /etc/mtab

You should able to see the following entry:
sudo gedit /etc/mtab

/dev/sda1 /media/disk fuseblk rw,nosuid,nodev,noatime,allow_other,allow_other,blksize=4096 0 0

Note: Above had been tested in ubuntu -8.04