Friday, December 25, 2009

Java : Copy source file to destination directory

This is simple java program to copy a particular source file to destination directory. Just provide a source file (file which is to copy) and provide a destination directory where to file to be coppied, lets look at the code

/* CopyFile.java */

import java.io.*;

public class CopyFile
{
public void copy(File srcFile,File destDirectory)
{
try
{
String srcFilePath = srcFile.getPath();

String fileName = srcFilePath.substring(srcFilePath.lastIndexOf("\\")+1);

File destFile = new File(destDirectory.getPath()+"\\"+fileName);

InputStream inSrc = new FileInputStream(srcFile);

OutputStream outDest = new FileOutputStream(destFile);

byte[] buffer = new byte[4096];
int bytesRead;

while ((bytesRead = inSrc.read(buffer)) > 0)
{
outDest.write(buffer, 0, bytesRead);
}

inSrc.close();
outDest.close();

System.out.println("File copy sucessfully : "+fileName);
}
catch (IOException ex)
{
System.out.println("Exception in copy : "+ex);
}
}

public static void main(String[] args)
{
CopyFile cf = new CopyFile();

cf.copy(new File("C:\\Downloads\\Test.zip"),new File("D:\\Work\\Files"));
}
}

Saturday, November 21, 2009

Java : Compare two dates using Date or Calendar class

Many times while programming in java we need to compare two dates, below are the two methods can be used to compare 2 dates, it can be done using either Date class or Calendar class. Below both program produces same output.

Method 1 : Using Date class

/* CompareDate.java */

import java.util.*;
import java.text.*;

public class CompareDate
{
public static void main(String[] args)
{
String date1 = "10-11-2009";//any date

String date2 = "10-11-2009";//any date

SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");

Date d1 = null;
Date d2 = null;

try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}


int results = d1.compareTo(d2);


if(results > 0)
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (results < 0)
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //results = 0
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}



Method 2 : Using Calendar class

/* CompareDate.java */

import java.util.*;
import java.text.*;

public class CompareDate
{
public static void main(String[] args)
{
String date1 = "15-11-2009";//any date

String date2 = "11-11-2009";//any date

SimpleDateFormat formatterDate = new SimpleDateFormat("dd-MM-yyyy");

Date d1 = null;
Date d2 = null;

try
{
d1 = formatterDate.parse(date1);
d2 = formatterDate.parse(date2);
}
catch (Exception e)
{
System.out.println("Parse Exception :"+e);
}

Calendar ss=Calendar.getInstance();
Calendar ee=Calendar.getInstance();


ss.setTime(d1);
ee.setTime(d2);


if(d1.after(d2))
{
System.out.println("d1 "+date1+" is greater than d2 "+date2);
}
else if (d1.before(d2))
{
System.out.println("d1 "+date1+" is less than d2 "+date2);
}
else //d1.equals(d2)
{
System.out.println("d1 "+date1+" is equal to d2 "+date2);
}
}
}

Tuesday, October 20, 2009

Java : Simple XML Parser

/* SimpleXmlParser.java */

import javax.xml.parsers.*;
import org.w3c.dom.*;

public class SimpleXmlParser
{
public static void main(String[] args)
{
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

Document dom = null;

try
{
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();

dom = db.parse("xmlFile.xml");

//get the root elememt
Element docEle = dom.getDocumentElement();

//get a nodelist of slot elements
NodeList nl = docEle.getElementsByTagName("Employee");

if(nl != null && nl.getLength() > 0)
{
for(int i = 0 ; i < nl.getLength();i++)
{
System.out.println("--Employee--");

Element el = (Element)nl.item(i);

System.out.println("Name : "+getTextValue(el,"Name"));
System.out.println("Designation : "+getTextValue(el,"Designation"));
System.out.println("Department : "+getTextValue(el,"Department"));
}
}
}
catch(Exception ex)
{
System.out.println("Exception : "+ex);
}
}

public static String getTextValue(Element ele, String tagName)
{
String textVal = null;
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0)
{
Element el = (Element)nl.item(0);
textVal = el.getFirstChild().getNodeValue();
}

return textVal;
}
}


/* xmlFile.xml */

<AllEmployee>
<Employee>
<Name>Ram</Name>
<Designation>Programmer</Designation>
<Department>Development</Department>
</Employee>
<Employee>
<Name>Shyam</Name>
<Designation>TL</Designation>
<Department>Finanace</Department>
</Employee>
<Employee>
<Name>Geeta</Name>
<Designation>Manager</Designation>
<Department>HR</Department>
</Employee>
</AllEmployee>

Output

--Employee--
Name : Ram
Designation : Programmer
Department : Development
--Employee--
Name : Shyam
Designation : TL
Department : Finanace
--Employee--
Name : Geeta
Designation : Manager
Department : HR

Friday, October 16, 2009

Java : Implement console in textarea using swing or awt

Program to implement output console using JTextArea of swing or TextArea of awt. Here all output log ie (System.out.println("")) is redirected to textarea rather than console.

Here is the complete code, directly you can run this code and see output.


/* ImplementConsole.java */


import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.io.*;

public class ImplementConsole extends JFrame
{
JTextArea console;
JScrollPane sp_console;

ImplementConsole()
{
setSize(700,350);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

console = new javax.swing.JTextArea();
console.setColumns(50);
console.setRows(15);

console.setText("Console Output...");

sp_console = new javax.swing.JScrollPane(console);

add(sp_console);

System.setOut(new PrintStream(new JTextAreaOutputStream(console)));
System.setErr(new PrintStream(new JTextAreaOutputStream(console)));


//starting new Thread for log writing
new Thread(new Runnable()
{
public void run()
{ try
{
writeLog();
}
catch (Exception ie)
{ }
}
}).start();
}

//inner class
public class JTextAreaOutputStream extends OutputStream
{
JTextArea ta;

public JTextAreaOutputStream(JTextArea t)
{
super();
ta = t;
}

public void write(int i)
{
ta.append(Character.toString((char)i));
}

public void write(char[] buf, int off, int len)
{
String s = new String(buf, off, len);
ta.append(s);
}
}


//function to write console log
public void writeLog()
{
for(int i=0; i< 10000; i++)
{
System.out.println("Console output : "+i);

// Make sure the last line is always visible
console.setCaretPosition(console.getDocument().getLength());

//just taking pause of 50ms
try
{
Thread.currentThread().sleep(50);
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}

//to flush console log after specific number of lines.
if(console.getLineCount() > 1000)
console.setText("");
}
}

public static void main(String[] args)
{
JFrame obj = new ImplementConsole();
obj.setVisible(true);
}
}



Output

Java : Time elapsed counter using swing

Java program that calculates time elapsed from start time, using this you can implement stop watch. Logic is simple just get start time (time when program started) and increment the time counter by current time minus start time ie (elapsedTime = currentTime - starTime).

Here is the complete tested code, directly you can run this code and see output.


/* TimeElapsed.java */

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;

public class TimeElapsed extends JFrame
{
JLabel time;

long startTime = System.currentTimeMillis();

TimeElapsed()
{
setSize(380,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

time = new JLabel("");

time.setFont(new Font("SansSerif",Font.BOLD, 36));

time.setForeground(Color.MAGENTA);

add(time);

//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}

public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(getTimeElapsed());
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}

public String getTimeElapsed()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime = elapsedTime / 1000;

String seconds = Integer.toString((int)(elapsedTime % 60));
String minutes = Integer.toString((int)((elapsedTime % 3600) / 60));
String hours = Integer.toString((int)(elapsedTime / 3600));

if (seconds.length() < 2)
seconds = "0" + seconds;

if (minutes.length() < 2)
minutes = "0" + minutes;

if (hours.length() < 2)
hours = "0" + hours;

return hours+":"+minutes+":"+seconds;
}

public static void main(String[] args)
{
JFrame obj = new TimeElapsed();
obj.setVisible(true);
}
}



Output

Thursday, October 15, 2009

Java : Digital clock using swing

This is a simple program to implement digital clock using swing. However format of time can be modified to users desire format.

Here is the complete tested code, directly you can run this code.

/* ShowTime.java */

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.*;

public class ShowTime extends JFrame
{
JLabel time;

ShowTime()
{
setSize(300,200);
setTitle("http://simpleandeasycodes.blogspot.com/");
setLocation(100,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new GridBagLayout());

time = new JLabel("");

time.setFont(new Font("SansSerif",Font.BOLD, 36));

time.setForeground(Color.MAGENTA);

add(time);

//starting new Thread which will update time
new Thread(new Runnable()
{
public void run()
{ try
{
updateTime();
}
catch (Exception ie)
{ }
}
}).start();
}

public void updateTime()
{
try
{
while(true)
{
//geting Time in desire format
time.setText(new SimpleDateFormat("hh:mm:ss a").format(new java.util.Date()));
//Thread sleeping for 1 sec
Thread.currentThread().sleep(1000);
}
}
catch (Exception e)
{
System.out.println("Exception in Thread Sleep : "+e);
}
}

public static void main(String[] args)
{
JFrame obj = new ShowTime();
obj.setVisible(true);
}
}

Output

Java : Create Table in PDF file

Here is the program to create table in PDF file.

You need to download iText jar file to run this code. Get iText from http://www.lowagie.com/iText/download.html

Here is the complete code.

/* PDFTable.java */

import java.io.*;
import java.awt.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.Font;
// reference to Font is ambiguous
//java.awt.Font and com.lowagie.text.Font

public class PDFTable
{
public static void main(String arg[])throws Exception
{
Document document=new Document(PageSize.A4,50,10,10,10);

PdfWriter.getInstance(document,new FileOutputStream("PDFTable.pdf"));
document.open();
document.add(new Paragraph("Simple and Easy Codes"));
document.add(new Paragraph("http://simpleandeasycodes.blogspot.com/",FontFactory.getFont(FontFactory.COURIER, 14,Font.BOLD, new Color(255, 150, 200))));

Table table = new Table(3);

table.setBorderWidth(1);
table.setBorderColor(new Color(0, 0, 255));
table.setPadding(5);
table.setSpacing(5);

Cell cell = new Cell("header");
cell.setHeader(true);
cell.setColspan(3);
table.addCell(cell);
table.endHeaders();

cell = new Cell("example cell with colspan 1 and rowspan 2");
cell.setRowspan(2);
cell.setBorderColor(new Color(255, 0, 0));
table.addCell(cell);

table.addCell("1.1");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
table.addCell("cell test1");

cell = new Cell("big cell");
cell.setRowspan(2);
cell.setColspan(2);

table.addCell(cell);
table.addCell("cell test2");

document.add(table);


document.close();
}
}

Monday, October 12, 2009

Java : Simple program to generate PDF File

This a simple program to generate PDF file. You need to download iText jar file to run this code. Get iText from http://www.lowagie.com/iText/download.html

Here is the complete code.

/* MyFirstPDFFile.java */

import java.io.*;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class MyFirstPDFFile
{
public static void main(String arg[])throws Exception
{
Document document=new Document(PageSize.A4,50,10,10,10);

PdfWriter.getInstance(document,new FileOutputStream("MyFirstPDFFile.pdf"));
document.open();
document.add(new Paragraph("Simple and Easy Codes"));
document.add(new Paragraph("http://simpleandeasycodes.blogspot.com/"));
document.close();
}
}

Friday, August 28, 2009

Java : Simple program using Math class

Math class is present in java.lang package so no need to import, its there by default.
Math class provides all trigonometric functions like sin(), cos(), tan() etc. Also other functions like abs() for calculating absolute values, sqrt() for getting square root, pow(x,y) for calculating power of values etc and many other features. you can solve complex number problems. Also PI value by using Math.PI

lets see a simple example.



/* TestMathClass.java */


public class TestMathClass
{
public static void main(String[] args)
{
int angles[] = { 0, 30, 45, 60, 90, 180 };

System.out.println("----Trigonometric Values----");

for (int i=0;i< angles.length ;i++ )
{
double rad = Math.toRadians(angles[i]);

System.out.println("----Angle: " + angles[i]);
System.out.println("Sin: " + Math.sin(rad));
System.out.println("Cos: " + Math.cos(rad));
System.out.println("Tan: " + Math.tan(rad));
}

System.out.println("----Absolute Values----");

int i = 8;
int j = -5;
System.out.println("Absolute value of " + i + " is :" + Math.abs(i));
System.out.println("Absolute value of " + j + " is :" + Math.abs(j));

float f1 = 1.40f;
float f2 = -5.28f;
System.out.println("Absolute value of " + f1 + " is :" + Math.abs(f1));
System.out.println("Absolute value of " + f2 + " is :" + Math.abs(f2));

double d1 = 3.324;
double d2 = -9.324;
System.out.println("Absolute value of " + d1 + " is :" + Math.abs(d1));
System.out.println("Absolute value of " + d2 + " is :" + Math.abs(d2));

long l1 = 3L;
long l2 = -4L;
System.out.println("Absolute value of " + l1 + " is :" + Math.abs(l1));
System.out.println("Absolute value of " + l2 + " is :" + Math.abs(l2));


System.out.println("----Other Values----");

double x = 11.635;
double y = 2.76;

System.out.println("The value of e is " + Math.E);
System.out.println("exp(" + x + ") is " + Math.exp(x));
System.out.println("log(" + x + ") is " + Math.log(x));
System.out.println("pow(" + x + ", " + y + ") is " + Math.pow(x, y));
System.out.println("sqrt(" + x + ") is " + Math.sqrt(x));



System.out.println("The value of PI is : "+Math.PI);
}
}



/********OUTPUT*********/


----Trigonometric Values----
----Angle: 0
Sin: 0.0
Cos: 1.0
Tan: 0.0
----Angle: 30
Sin: 0.49999999999999994
Cos: 0.8660254037844387
Tan: 0.5773502691896257
----Angle: 45
Sin: 0.7071067811865475
Cos: 0.7071067811865476
Tan: 0.9999999999999999
----Angle: 60
Sin: 0.8660254037844386
Cos: 0.5000000000000001
Tan: 1.7320508075688767
----Angle: 90
Sin: 1.0
Cos: 6.123233995736766E-17
Tan: 1.633123935319537E16
----Angle: 180
Sin: 1.2246467991473532E-16
Cos: -1.0
Tan: -1.2246467991473532E-16
----Absolute Values----
Absolute value of 8 is :8
Absolute value of -5 is :5
Absolute value of 1.4 is :1.4
Absolute value of -5.28 is :5.28
Absolute value of 3.324 is :3.324
Absolute value of -9.324 is :9.324
Absolute value of 3 is :3
Absolute value of -4 is :4
----Other Values----
The value of e is 2.718281828459045
exp(11.635) is 112983.8311174165
log(11.635) is 2.454017796754255
pow(11.635, 2.76) is 874.0076417529531
sqrt(11.635) is 3.411011580162108
The value of PI is : 3.141592653589793

Friday, August 21, 2009

Java : Simple Thread Example

How to start new thread from main thread. Any program starts execution from main thread how ever you can start n numbers of threads from this main thread. Lets see a simple Thread example, just compile and run main program and see output.

/* MainClass.java */

public class MainClass
{
public static void main(String[] args)
{

System.out.println("Main Thread Started");

AnotherClass ac = new AnotherClass();
//Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
ac.start();

for(int i=0;i<=10 ;i++ )
{
System.out.println("Main "+i);

try
{
//Get current Thread
Thread.currentThread().sleep(300);
}
catch (InterruptedException ex)
{
//sleep() method throws this checked exception
System.out.println("Exception in MainClass thread : "+ex);
}

}
System.out.println("Ending Main Thread");
}
}


/* AnotherClass.java */


//Inheriting from thread class
public class AnotherClass extends Thread
{
//Overrideing rum method from thread class
public void run()
{
System.out.println("Another Thread Started");

for (int j=0;j<=10 ;j++ )
{
System.out.println("Another "+j);

try
{
//sleep() method can be used here directly becz it is publicly inherited from Thread class
sleep(100);
}
catch (InterruptedException ex)
{
//Handling InterruptedException rather to declare becz overriding function cannot throw any new checked exception
System.out.println("Exception in AnotherClass thread : "+ex);
}
}
System.out.println("Ending Another Thread");
}
}



/**********OUTPUT***************/

Main Thread Started
Main 0
Another Thread Started
Another 0
Another 1
Another 2
Main 1
Another 3
Another 4
Another 5
Main 2
Another 6
Another 7
Another 8
Main 3
Another 9
Another 10
Ending Another Thread
Main 4
Main 5
Main 6
Main 7
Main 8
Main 9
Main 10
Ending Main Thread

Java : Get System Input using Scanner class

Simple program to scan input from user using Scanner class. You can get Long, Shot, Byte, String, Int etc.


/* ScanInput.java */

import java.util.Scanner;

public class ScanInput
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);

System.out.println("Enter String : ");

String strVal = scan.nextLine();

System.out.println("You Entered : "+strVal);

System.out.println("Enter Int : ");

int intVal = scan.nextInt();

System.out.println("You Entered : "+intVal);

scan.close();

}
}


/******OUTPUT*********/


Enter String :
This is a string
You Entered : This is a string
Enter Int :
234
You Entered : 234

Java : Sorting and Randomly iterating Hashtable

As Hashtable is unordered and unsorted by default many time its required to sort it or randomly access its data. Same applicable with LinkedHashMap, TreeMap, HashMap.

In below example ArrayList is used to sort and shuffle Hashtable's key.


/* TestHash.java */

import java.util.*;

public class TestHash
{
public static void main(String[] args)
{
Hashtable<Integer,String> data = new Hashtable<Integer,String>();

//Temp ArrayList is used to store keys of Hashtable
ArrayList<Integer> temp = new ArrayList<Integer>();

data.put(1,"ABC");
data.put(0,"LMN");
data.put(5,"PQR");
data.put(3,"XYZ");

Integer key;

System.out.println("Default Unorderd and Unsorted");
//Iterating Hashtable
Enumeration<Integer> enu = data.keys();
while(enu.hasMoreElements())
{
key=enu.nextElement();
System.out.println(key+" "+data.get(key));

//Putting Hashtable keys in ArrayList
temp.add(key);
}

//Sorting keys of Hashtable
Collections.sort(temp);

//iterating ArrayList using for each loop
System.out.println("Sorted");
for (Integer val : temp)
{
System.out.println(val+" "+data.get(val));
}

//Shuffling keys of Hashtable
Collections.shuffle(temp);

//iterating ArrayList using for each loop
System.out.println("Randomly Iterating");
for (Integer val : temp)
{
System.out.println(val+" "+data.get(val));
}

}
}


/******OUTPUT*******/

Default Unorderd and Unsorted
5 PQR
3 XYZ
1 ABC
0 LMN
Sorted
0 LMN
1 ABC
3 XYZ
5 PQR
Randomly Iterating
3 XYZ
0 LMN
5 PQR
1 ABC

Java : Iterating ArrayList

Program to Iterate ArrayList, You can iterate ArrayList of String, Integer, Double, Long, Byte, Character etc.

1st Method simple standard way to iterate.
2nd Method using for each loop.


/* IterateArrayList.java */

import java.util.ArrayList;

public class IterateArrayList
{
public static void main(String[] args)
{
ArrayList<Integer> data = new ArrayList<Integer>();

for (int i=0;i<10 ;i++ )
{
//Java 5 supports Autoboxing (int added in Arraylist)
data.add(i);
}

System.out.println("Iterateing using 1st Method");

//Iterating ArrayList
for (int i=0;i<data.size() ;i++ )
{
System.out.println(data.get(i));
}


System.out.println("Iterateing using 2st Method");

//Iterating using for each loop
for(Integer val : data)
{
System.out.println(val);
}
}
}


/********OUTPUT********/
Iterateing using 1st Method
0
1
2
3
4
5
6
7
8
9
Iterateing using 2st Method
0
1
2
3
4
5
6
7
8
9

Friday, August 14, 2009

Java : Generate CSV File

This is simple program to generate CSV file. As we know csv is nothing but comma separated values, so we will write file with '.csv' extension.


/* GenerateCSVFile.java*/

import java.io.*;

public class GenerateCSVFile
{
public static void main(String[] args)
{
//name of the file, it takes default path ie. current directory
//you can also provide absolute/relative path
String CSVFileToWrite = "MyCSVFile.csv";//file with .csv extension

try
{
File file=new File(CSVFileToWrite);
FileWriter fw =new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

for(int line = 0 ; line < 10 ; line ++)
{
bw.write("A"+line+",B"+line+",C"+line);//writing comma separated values
bw.newLine();
bw.flush();//flushing
}

bw.close();//closing BufferedWriter

System.out.println("File generated sucessfully : "+file.getAbsolutePath());

}
catch (IOException ex)
{
ex.printStackTrace();
}

}
}

Java : Generate Random Numbers between minimum and maximum range.

This is simple java program to generate random numbers between minimum and maximum (both inclusive) given range. For example in below code input minimum number is 200 and maximum number is 300.

/* RandomNumber.java*/

import java.util.Random;

public class RandomNumber
{
public static void main(String[] args)
{
int min = 200;
int max = 300;

Random ran = new Random();

for (int i=0;i<10 ;i++ )
{
System.out.println(ran.nextInt(max - min + 1) + min);
}
}
}



/*****OUTPUT*****/

272
251
214
245
246
228
240
212
294
285

Thursday, August 6, 2009

Java : Date and Time Formats and Calendar Class

Java Date and Time Formats



Customized Date and Time Formats
PatternOutput
dd MMMM yyyy EEEE06 August 2009 Thursday
dd.MM.yy06.08.09
yyyy.MM.dd G 'at' hh:mm:ss z2009.08.06 AD at 04:26:45 IST
EEE, MMM d, ''yyThu, Aug 6, '09
hh:mm:ss:SSS a04:40:52:110 PM
HH:mm z16:41 IST
dd/MM/yyyy EE06/08/2009 Thu
dd-MMM-yyyy hh:mm:ss a EEEE06-Aug-2009 04:36:22 PM Thursday


Simple Java program to get today's date,yesterday's date and tomorrow's date using Calendar class.

/* GetDate.java */

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class GetDate
{
public static void main(String[] args)
{
//get yesterday's date
Calendar calYesterday = Calendar.getInstance();
calYesterday.add(Calendar.DAY_OF_MONTH, -1);
String yesterday=new SimpleDateFormat("dd/MM/yyyy").format(calYesterday.getTime());

//get today's date
Calendar calToday = Calendar.getInstance();
String today=new SimpleDateFormat("dd/MM/yyyy").format(calToday.getTime());

//get tomorrow's date
Calendar calTomorrow = Calendar.getInstance();
calTomorrow.add(Calendar.DAY_OF_MONTH, +1);
String tomorrow=new SimpleDateFormat("dd/MM/yyyy").format(calTomorrow.getTime());


System.out.println("Yesterday : "+yesterday);

System.out.println("Today : "+today);

System.out.println("Tomorrow : "+tomorrow);

}
}

/*******OUTPUT********/

Yesterday : 05/08/2009
Today : 06/08/2009
Tomorrow : 07/08/2009

You can also use Date class to get today's date

//String today = new SimpleDateFormat("dd/MM/yyyy").format(new java.util.Date());


Calendar Class




Lets look at a program for testing Calendar fields.

/* CalendarField.java */

import java.util.Calendar;

public class CalendarField
{
public static void main(String[] args)
{
//get today's date
Calendar calToday = Calendar.getInstance();

//Field indicating the day of the month.
System.out.println("DATE : "+calToday.get(Calendar.DATE));

//Field indicating the month.
System.out.println("MONTH : "+calToday.get(Calendar.MONTH ));

//Field indicating the day of the month.
System.out.println("DAY_OF_MONTH : "+calToday.get(Calendar.DAY_OF_MONTH ));

//Field indicating the day of the week.
System.out.println("DAY_OF_WEEK : "+calToday.get(Calendar.DAY_OF_WEEK ));

//Field indicating the ordinal number of the day of the week within the current month.
System.out.println("DAY_OF_WEEK_IN_MONTH : "+calToday.get(Calendar.DAY_OF_WEEK_IN_MONTH ));

//Field indicating the day number within the current year.
System.out.println("DAY_OF_YEAR : "+calToday.get(Calendar.DAY_OF_YEAR ));

//Field indicating the week number within the current month.
System.out.println("WEEK_OF_MONTH : "+calToday.get(Calendar.WEEK_OF_MONTH ));

//Field indicating the hour of the day.
System.out.println("HOUR_OF_DAY : "+calToday.get(Calendar.HOUR_OF_DAY ));

//Field indicating the hour of the morning or afternoon.
System.out.println("HOUR : "+calToday.get(Calendar.HOUR ));

//Field indicating the minute within the hour.
System.out.println("MINUTE : "+calToday.get(Calendar.MINUTE ));

//Field indicating the second within the minute.
System.out.println("SECOND : "+calToday.get(Calendar.SECOND));

//Field indicating the millisecond within the second.
System.out.println("MILLISECOND : "+calToday.get(Calendar.MILLISECOND ));

//Field indicating the year.
System.out.println("YEAR : "+calToday.get(Calendar.YEAR ));

//Field indicating the week number within the current year.
System.out.println("WEEK_OF_YEAR : "+calToday.get(Calendar.WEEK_OF_YEAR ));

//Field indicating the era, e.g., AD or BC in the Julian calendar.
System.out.println("ERA : "+calToday.get(Calendar.ERA ));
}
}


/*******OUTPUT********/

DATE : 6
MONTH : 7
DAY_OF_MONTH : 6
DAY_OF_WEEK : 5
DAY_OF_WEEK_IN_MONTH : 1
DAY_OF_YEAR : 218
WEEK_OF_MONTH : 2
HOUR_OF_DAY : 19
HOUR : 7
MINUTE : 40
SECOND : 47
MILLISECOND : 157
YEAR : 2009
WEEK_OF_YEAR : 32
ERA : 1

Tuesday, August 4, 2009

java.lang.NoSuchMethodError: com.caucho.server.connection.CauchoRequest.isInitial()Z

500 Servlet Exception


[show] java.lang.NoSuchMethodError: com.caucho.server.connection.CauchoRequest.isInitial()Z

java.lang.NoSuchMethodError: com.caucho.server.connection.CauchoRequest.isInitial()Z
   at com.caucho.server.connection.AbstractHttpResponse.finishInvocation(AbstractHttpResponse.java:2271)
   at com.caucho.server.connection.AbstractHttpResponse.finishInvocation(AbstractHttpResponse.java:2237)
   at com.caucho.server.connection.AbstractHttpResponse.sendError(AbstractHttpResponse.java:567)
   at com.caucho.server.connection.AbstractHttpResponse.sendError(AbstractHttpResponse.java:525)
   at com.caucho.server.connection.HttpServletResponseImpl.sendError(HttpServletResponseImpl.java:277)
   at com.caucho.servlets.FileServlet.service(FileServlet.java:274)
   at com.caucho.server.dispatch.ServletFilterChain.doFilter(ServletFilterChain.java:103)
   at com.caucho.server.webapp.WebAppFilterChain.doFilter(WebAppFilterChain.java:189)
   at com.caucho.server.dispatch.ServletInvocation.service(ServletInvocation.java:266)
   at com.caucho.server.http.HttpRequest.handleRequest(HttpRequest.java:292)
   at com.caucho.server.port.TcpConnection.handleRequests(TcpConnection.java:577)
   at com.caucho.server.port.TcpConnection$AcceptTask.doAccept(TcpConnection.java:1211)
   at com.caucho.server.port.TcpConnection$AcceptTask.run(TcpConnection.java:1152)
   at com.caucho.util.ThreadPool$Item.runTasks(ThreadPool.java:759)
   at com.caucho.util.ThreadPool$Item.run(ThreadPool.java:681)
   at java.lang.Thread.run(Thread.java:619)

Resin/3.2.1 Server: ''




Hi friends,
I am getting this error on my Resin 3.2.1 web server, i tried lot to solve this error but could not succeed. This error comes when i refresh my pages, many times images does not appears or css not supported.
I tried reinstalling JAVA also reinstalling Resin but could not succeed to solve this error. I searched on net to solve this exception but did not found any source.

Any one getting same exception??
What reason it could be??
How to solve this Exception??

Javascript : Simple Digital / Analog clock

Digital Clock



<HTML>
<HEAD>
<TITLE> Digital Clock </TITLE>
<script type="text/javascript">

function updateClock ( )
{
var currentTime = new Date ( );

var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );

// Pad the minutes and seconds with leading zeros, if required
currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

// Choose either "AM" or "PM" as appropriate
var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

// Convert the hours component to 12-hour format if needed
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

// Convert an hours component of "0" to "12"
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

// Compose the string for display
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

// Update the time display
document.getElementById("clock").innerHTML = currentTimeString;
}
</script>

</HEAD>

<BODY onload="updateClock(); setInterval('updateClock()', 1000 )">
<div id="clock"> </div>
</BODY>
</HTML>


Analog Clock



<HTML>
<HEAD>
<TITLE> Analog Clock </TITLE>
<script type="text/javascript">

window.CoolClock = function(canvasId,displayRadius,skinId,showSecondHand,gmtOffset)
{
return this.init(canvasId,displayRadius,skinId,showSecondHand,gmtOffset);
}

CoolClock.findAndCreateClocks = function()
{
var canvases = document.getElementsByTagName("canvas");
for (var i=0;i<canvases.length;i++)
{
var fields = canvases[i].className.split(" ")[0].split(":");
if (fields[0] == "CoolClock")
{
new CoolClock(canvases[i].id,fields[2],fields[1],fields[3]!="noSeconds",fields[4]);
}
}
}

CoolClock.addLoadEvent = function(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
window.onload = func;
else
window.onload = function()
{
oldonload();
func();
}
}

CoolClock.config =
{
clockTracker: {},
tickDelay: 1000,
longTickDelay: 15000,
defaultRadius: 85,
renderRadius: 100,
defaultSkin: "swissRail",
skins:
{
swissRail:
{
outerBorder: { lineWidth: 1, radius:95, color: "black", alpha: 1 },
smallIndicator: { lineWidth: 2, startAt: 89, endAt: 93, color: "black", alpha: 1 },
largeIndicator: { lineWidth: 4, startAt: 80, endAt: 93, color: "black", alpha: 1 },
hourHand: { lineWidth: 8, startAt: -15, endAt: 50, color: "black", alpha: 1 },
minuteHand: { lineWidth: 7, startAt: -15, endAt: 75, color: "black", alpha: 1 },
secondHand: { lineWidth: 1, startAt: -20, endAt: 85, color: "red", alpha: 1 },
secondDecoration: { lineWidth: 1, startAt: 70, radius: 4, fillColor: "red", color: "red", alpha: 1 }
}
}
};

CoolClock.prototype =
{
init: function(canvasId,displayRadius,skinId,showSecondHand,gmtOffset) {
this.canvasId = canvasId;
this.displayRadius = displayRadius || CoolClock.config.defaultRadius;
this.skinId = skinId || CoolClock.config.defaultSkin;
this.showSecondHand = typeof showSecondHand == "boolean" ? showSecondHand : true;
this.tickDelay = CoolClock.config[ this.showSecondHand ? "tickDelay" : "longTickDelay"];

this.canvas = document.getElementById(canvasId);

this.canvas.setAttribute("width",this.displayRadius*2);
this.canvas.setAttribute("height",this.displayRadius*2);

this.canvas.style.width = this.displayRadius*2 + "px";
this.canvas.style.height = this.displayRadius*2 + "px";

this.renderRadius = CoolClock.config.renderRadius;

this.scale = this.displayRadius / this.renderRadius;
this.ctx = this.canvas.getContext("2d");
this.ctx.scale(this.scale,this.scale);

this.gmtOffset = gmtOffset != null ? parseFloat(gmtOffset) : gmtOffset;

CoolClock.config.clockTracker[canvasId] = this;
this.tick();
return this;
},
fullCircle: function(skin)
{
this.fullCircleAt(this.renderRadius,this.renderRadius,skin);
},
fullCircleAt: function(x,y,skin)
{
with (this.ctx)
{
save();
globalAlpha = skin.alpha;
lineWidth = skin.lineWidth;
if (!document.all)
beginPath();
if (document.all)
// excanvas doesn't scale line width so we will do it here
lineWidth = lineWidth * this.scale;
arc(x, y, skin.radius, 0, 2*Math.PI, false);
if (document.all)
// excanvas doesn't close the circle so let's color in the gap
arc(x, y, skin.radius, -0.1, 0.1, false);
if (skin.fillColor)
{
fillStyle = skin.fillColor
fill();
}
else
{
// XXX why not stroke and fill
strokeStyle = skin.color;
stroke();
}
restore();
}
},
radialLineAtAngle: function(angleFraction,skin)
{
with (this.ctx) {
save();
translate(this.renderRadius,this.renderRadius);
rotate(Math.PI * (2 * angleFraction - 0.5));
globalAlpha = skin.alpha;
strokeStyle = skin.color;
lineWidth = skin.lineWidth;
if (document.all)
// excanvas doesn't scale line width so we will do it here
lineWidth = lineWidth * this.scale;
if (skin.radius)
{
this.fullCircleAt(skin.startAt,0,skin)
}
else
{
beginPath();
moveTo(skin.startAt,0)
lineTo(skin.endAt,0);
stroke();
}
restore();
}
},
render: function(hour,min,sec)
{
var skin = CoolClock.config.skins[this.skinId];
this.ctx.clearRect(0,0,this.renderRadius*2,this.renderRadius*2);

this.fullCircle(skin.outerBorder);

for (var i=0;i<60;i++)
this.radialLineAtAngle(i/60,skin[ i%5 ? "smallIndicator" : "largeIndicator"]);

this.radialLineAtAngle((hour+min/60)/12,skin.hourHand);
this.radialLineAtAngle((min+sec/60)/60,skin.minuteHand);
if (this.showSecondHand)
{
this.radialLineAtAngle(sec/60,skin.secondHand);
if (!document.all)
// decoration doesn't render right in IE so lets turn it off
this.radialLineAtAngle(sec/60,skin.secondDecoration);
}
},
nextTick: function()
{
setTimeout("CoolClock.config.clockTracker['"+this.canvasId+"'].tick()",this.tickDelay);
},

stillHere: function()
{
return document.getElementById(this.canvasId) != null;
},
refreshDisplay: function()
{
var now = new Date();
if (this.gmtOffset != null)
{
// use GMT + gmtOffset
var offsetNow = new Date(now.valueOf() + (this.gmtOffset * 1000 * 60 * 60));
this.render(offsetNow.getUTCHours(),offsetNow.getUTCMinutes(),offsetNow.getUTCSeconds());
}
else
{
// use local time
this.render(now.getHours(),now.getMinutes(),now.getSeconds());
}
},
tick: function()
{
if (this.stillHere())
{
this.refreshDisplay()
this.nextTick();
}
}
}

CoolClock.addLoadEvent(CoolClock.findAndCreateClocks);


</script>
</HEAD>

<BODY>
<canvas id="c1" class="CoolClock"></canvas>
</BODY>
</HTML>

Tuesday, July 28, 2009

Java : Get all Dates/Days between range of start date and end date

This is Simple java program to get all dates with days between range of start date and end date. Here date format used dd/MM/yyyy however any time you can customize it to your desire format. In below program just provide input start date and end date and see output.


/* ParseDate.java */

import java.util.*;
import java.text.*;

public class ParseDate
{
public static void main(String[] args)
{
String strdate = "25/07/2009";//any start date

String enddate = "03/08/2009";//any end date

SimpleDateFormat formatterDate = new SimpleDateFormat("dd/MM/yyyy");

SimpleDateFormat formatterDay = new SimpleDateFormat("dd/MM/yyyy EEEE");

Date st = null;
Date ed = null;

try
{
st = formatterDate.parse(strdate);
ed = formatterDate.parse(enddate);
}
catch (ParseException e)
{
System.out.println("Parse Exception :"+e);
}

Calendar ss=Calendar.getInstance();
Calendar ee=Calendar.getInstance();


ss.setTime(st);
ee.setTime(ed);
ee.add(Calendar.DATE,1);//just incrementing end date by 1

String day = "";

while(!ss.equals(ee))
{
day = formatterDay.format(ss.getTime());

System.out.println(day);

ss.add(Calendar.DATE,1);
}

}
}

/********INPUT************/

String strdate = "25/07/2009";//any start date

String enddate = "03/08/2009";//any end date

/********OUTPUT**********/

25/07/2009 Saturday
26/07/2009 Sunday
27/07/2009 Monday
28/07/2009 Tuesday
29/07/2009 Wednesday
30/07/2009 Thursday
31/07/2009 Friday
01/08/2009 Saturday
02/08/2009 Sunday
03/08/2009 Monday

Monday, July 20, 2009

JSP: Develop simple WAP page

WAP stands for Wireless Application Protocol. Basically wap pages are made for mobile browser. Lets try to understand how to make wap pages using JSP

Few terms required to understand before starting for developing a WAP site

MSISDN
MSISDN stands for "Mobile Subscriber Integrated Services Digital Network Number" is nothing but phone number.

USER AGENT
A user agent is the client application used with a particular network protocol.
When you visit a Web page, your browser sends the user-agent string to the server
hosting the site that you are visiting. This string indicates which browser you
are using, its version number, and details about your system, such as operating
system and version. The Web server can use this information to provide content that
is tailored for your specific browser.With the help of user agen we can detect user phone type (handset).

X WAP PROFILE
X Wap profile is mostly a xml file which contains complete details of a particular
mobile phone.X Wap profile contain details like screen size, midpi etc. etc.

Few examples of X Wap profile

Nokia 3110c"http://nds1.nds.nokia.com/uaprof/N3110cr100.xml"
NokiaE71"http://nds1.nds.nokia.com/uaprof/NE71-1r100.xml"
SonyEricssonK750c"http://wap.sonyericsson.com/UAprof/K750cR101.xml"
SAMSUNG-SGH-J210"http://wap.samsungmobile.com/uaprof/SGH-J210.xml"
LG-KG195"http://gsm.lge.com/html/gsm/LG-UAP-KG195-v0.1.xml"


if you want x wap profile of any handset just mail me at madan712@gmail.com


Lets look at a simple jsp code for a wap page.


<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<%@ page import="java.net.*,java.io.*" %>
<%!
//This function is just used to get mobile Screen size
public static String getScreenSize(String x_wap_profile)
{
x_wap_profile = x_wap_profile.replaceAll("\"","");

String screen_size = "";

try
{
URL url= new URL(x_wap_profile);

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";



while((line=in.readLine()) != null)
{
line = line.trim();
if(line.startsWith("<prf:ScreenSize>"))
{

line = line.replaceAll("<prf:ScreenSize>","");
line = line.replaceAll("</prf:ScreenSize>","");

screen_size = line;

break;
}
}

//closing resource
in.close();
connection=null;
}
catch(Exception ex)
{
//any default value
screen_size = "128x160";
}


//System.out.println("screen_size : "+screen_size);

return screen_size;
}
%>
<%
// get phone number
String phone_number = request.getHeader("x-nokia-msisdn");
if(phone_number==null)
phone_number = request.getHeader("x-msisdn");
if(phone_number==null)
phone_number = request.getHeader("X-msisdn");
if(phone_number==null)
phone_number = request.getHeader("X-MSISDN");
if(phone_number==null)
phone_number = request.getHeader("msisdn");
if(phone_number==null)
phone_number = request.getHeader("Nokia-msisdn");

String user_agent = request.getHeader("USER-AGENT");

//String phone_type = user_user_agent.substring(0,user_user_agent.indexOf("/"));

String phone_type = "";

int in = user_agent.indexOf("/");
if(in > 0)
phone_type=user_agent.substring(0,in);

if(phone_type.toUpperCase().startsWith("MOZILLA") )
{
phone_type = user_agent.substring(user_agent.indexOf("Nokia"),user_agent.indexOf("/",user_agent.indexOf("Nokia")) );
}

String x_wap_profile = request.getHeader("x-wap-profile");

String screen_size = getScreenSize(x_wap_profile);
%>
<body align='left' topmargin='0' bottommargin='0' leftmargin='0' rightmargin='0' marginheight='0' marginwidth='0'>
<table border='1' cellspacing='0' cellpadding='0'>
<tr><td>Phone number</td><td><%= phone_number %></td></tr>
<tr><td>User agent</td><td><%= user_agent %></td></tr>
<tr><td>Phone type</td><td><%= phone_type %></td></tr>
<tr><td>X wap profile</td><td><%= x_wap_profile %></td></tr>
<tr><td>Screen size</td><td><%= screen_size %></td></tr>
</table>
</body>
</html>

Output of Nokia 3110c handset

Phone number919892558621
User agentNokia3110c/2.0(04.91)Profile/MIDP-2.0Configuration/CLDC-1.1
Phone typeNokia3110c
X wap profile"http://nds1.nds.nokia.com/uaprof/N3110cr100.xml"
Screen size128x160



Now two questions might have arise in your mind -
1. How do i test and debug these codes?
2. Mobiles screen are of different sizes, how same page get render in all handsets?

How to test and debug wap pages?

Answer of first question is simple, there is a tool available call Modify Headers which you can set in Mozilla fire fox browser by searching Add-ons. Just go to Tools -> Add-ons -> Get Add-ons. Search for Modify Headers.



Above shown screen shot show Modify Headers Add-ons, You can view it by clicking on Tools -> modify Headers.

Now atleast add two headers like
1. Name : user-agent
Value : Nokia3110c/Xyz (any handset name)
2. Name : msisdn
Value : 919892858621 (any mobile number)

Optionally u can also set x-wap-profile.

This is how you will get all features tested on browser same as it will work on mobile phone.

How to handle different screen sizes on different handsets?

Answer of the second question is still remaining. Here is how it goes...

Mostly Horizontal scroll is not allowed in a WAP page, to avoid you need to specify width of the page. if you modify above used function getScreenSize, you will get width of that particular handset. Different Screen sizes available are :

96x65,128x96,128x128,128x144,128x160,176x144,176x208,176x220,208x144,208x208,
208x320,240x320,320x240,322x320,350x380,352x416,360x640,400x340,400x400,505x190.

Lets look at another jsp code.

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<%@ page import="java.net.*,java.io.*" %>
<%!
//This function is just used to get screen width
public static String getScreenWidth(String x_wap_profile)
{
x_wap_profile = x_wap_profile.replaceAll("\"","");

String screen_size = "";

String width = "";

try
{
URL url= new URL(x_wap_profile);

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";



while((line=in.readLine()) != null)
{
line = line.trim();
if(line.startsWith("<prf:ScreenSize>"))
{

line = line.replaceAll("<prf:ScreenSize>","");
line = line.replaceAll("</prf:ScreenSize>","");

screen_size = line;

break;
}
}

//closing resource
in.close();
connection=null;
}
catch(Exception ex)
{
//any default
screen_size = "128x160";
}

width=screen_size.substring(0,screen_size.indexOf("x"));


//System.out.println("screen_size : "+screen_size);

return width;
}
%>
<%

String user_agent = request.getHeader("USER-AGENT");

//String phone_type = user_user_agent.substring(0,user_user_agent.indexOf("/"));

String phone_type = "";

int in = user_agent.indexOf("/");
if(in > 0)
phone_type=user_agent.substring(0,in);

if(phone_type.toUpperCase().startsWith("MOZILLA") )
{
phone_type = user_agent.substring(user_agent.indexOf("Nokia"),user_agent.indexOf("/",user_agent.indexOf("Nokia")) );
}

String x_wap_profile = request.getHeader("x-wap-profile");

String width = getScreenWidth(x_wap_profile);
%>
<body align='left' topmargin='0' bottommargin='0' leftmargin='0' rightmargin='0' marginheight='0' marginwidth='0' style="width: <%=width%>px;">
<table border='1' cellspacing='0' cellpadding='0' width='<%=width%>'>
<tr><td>Phone: <%= phone_type %></td></tr>
<tr><td>Screen width : <%= width %></td></tr>
<tr><td>Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here </td></tr>
</table>
</body>
</html>


Output on different Handsets

Phone: Nokia3110c
Screen width : 128
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here
Phone: Nokia6600
Screen width : 176
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here
Phone: NokiaN82
Screen width : 240
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here
Phone: NokiaE71
Screen width : 320
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here


My personal experience

Working with WAP pages (mobile browser) is more difficult than working with WEB pages (windows browser).

Few things to be noted to develop a wap pages, all tags must have its closing tags like <td>..</td> even for a single tags must be like <br/> and not <br>, <br> is wrong when you work on wap page.

All quotes must have be in single quotes '' and not double quotes "" for eg. <td colspan='2'> and not <td colspan="2">

ie. Follow XHTML convension

Also don't forget to include DOCTYPE

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

Because its painful when same things works on one phone and does not works on other phone. Also many other problems arises when you work on wap pages.

Plz do write your comments, any queries/help plz write me on madan712@gmail.com

Thursday, July 16, 2009

Java: Simple URLConnection program

Simple java program to Read from a URLConnection

/* SimpleURLConnection.java */

import java.net.*;
import java.io.*;

public class SimpleURLConnection
{
public static void main(String[] args) throws Exception
{
URL url= new URL("http://10.10.2.215/URLConnection/Test.jsp");//provide proper url

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";

while((line=in.readLine()) != null)
{
System.out.println(line);
}

//closing resource
in.close();
connection=null;
}
}


Same above example in detail

/* SimpleURLConnection.java */


import java.net.URLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.net.MalformedURLException;
import java.io.IOException;

public class SimpleURLConnection
{
public static void main(String[] args)
{
//Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
URL url = null;
/*The abstract class URLConnection is the superclass of all classes that represent a communications
link between the application and a URL. Instances of this class can be used both to read from and to
write to the resource referenced by the URL*/
URLConnection connection = null;
BufferedReader in = null;

try
{
//Creates a URL object from the String representation.
url= new URL("http://10.10.2.215/URLConnection/Test.jsp");

}
catch (MalformedURLException ex)
{
//If the string specifies an unknown protocol.
System.out.println(ex);
}

try
{
//Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
connection = url.openConnection();

in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";

while((line=in.readLine()) != null)
{
System.out.println(line);
}
//closing BufferedReader
in.close();
}
catch (IOException ex)
{
//if an I/O exception occurs.
System.out.println(ex);
}

connection=null;
}
}

MS SQL: Join tables of different database

Assume you have two database, Db1 and Db2.

Employee table is in Db1 and Department in Db2

Query:

select emp_name, dept_name from Db1.dbo.Employee a, Db2.dbo.Department b where a.dept_id = b.dept_id

Syntax is Database name followed by .dbo. followed by table name

eg. Db1.dbo.Employee

Similarly you can use above syntax for any type of query.

Saturday, July 11, 2009

Javascript : Creating Back button

Back buttons are used to return to the previous page. This is the same as using the back button on your browser.

You can use below codes in HTML/JSP etc pages.

Creating Back Button

<FORM><INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);return true;"> </FORM>

The javascript:history.go(-1) code displays the previous page.Change the value of -1 to any number of pages you would like to send your visitors back

Instead of Button you can also used it for any link or image.

An image used as back button.

<A HREF="javascript:history.go(-1)">
<IMG SRC="images/back.gif"
BORDER="0"></A>


A standard link as back button.

<A HREF="javascript:history.go(-1)"> [Go Back]</A>



MS SQL: Get Day/Month of Date



1.This is simple query, which gives Date
select GETDATE()
output:
2009-07-11 19:56:18.543

2.This query give day and month
select DATENAME(dw,GETDATE()) as Day, DATENAME(mm,GETDATE()) as Month
output:
Saturday July

3:This query gives individual date, month, year
select DAY(GETDATE()) as Date,MONTH(GETDATE()) as Month,YEAR(GETDATE()) as Year
output:
11 7 2009


Friday, July 10, 2009

Java: URL Encoder/Decoder

/* Simple java program for Encoding and Decoding URL
Below is complete tested code, directly you can run this program
*/

//SimpleURLEncoder.java

import java.net.*;

public class SimpleURLEncoder
{
public static void main(String[] args) throws Exception
{
String userUrl = "http://10.10.3.24/Product.jsp?username=scott&password=tiget";
URL url = url = new URL(userUrl);
String encodedUrl = encodedUrl = URLEncoder.encode(url.toString(),"UTF-8");
String decodedUrl = decodedUrl = URLDecoder.decode(encodedUrl,"UTF-8");

System.out.println("userUrl : "+userUrl);

System.out.println("encodedUrl : "+encodedUrl);
System.out.println("decodedUrl : "+decodedUrl);

}
}


/***************OUTPUT*****************/


userUrl : http://10.10.3.24/Product.jsp?username=scott&password=tiget
encodedUrl : http%3A%2F%2F10.10.3.24%2FProduct.jsp%3Fusername%3Dscott%26password
%3Dtiget
decodedUrl : http://10.10.3.24/Product.jsp?username=scott&password=tiget




//Same above example in detail


import java.net.*;//for URL
import java.io.*;//for UnsupportedEncodingException

public class SimpleURLEncoder
{
public static void main(String[] args)
{
String userUrl = "http://10.10.3.24/Product.jsp?username=scott&password=tiget";
URL url = null;
String encodedUrl = "";
String decodedUrl = "";

try
{
//Creates a URL object from the String representation.
url = new URL(userUrl);
}
catch (MalformedURLException ex)
{
//If the string specifies an unknown protocol.
System.out.println("MalformedURLException : "+ex);
}

try
{
encodedUrl = URLEncoder.encode(url.toString(),"UTF-8");
//UTF-8 : The name of a supported character encoding.
//The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.
}
catch (UnsupportedEncodingException ex)
{
//If the named encoding is not supported
System.out.println("UnsupportedEncodingException : "+ex);
}

try
{
decodedUrl = URLDecoder.decode(encodedUrl,"UTF-8");
}
catch (UnsupportedEncodingException ex)
{
//If the named encoding is not supported
System.out.println("UnsupportedEncodingException : "+ex);
}

System.out.println("userUrl : "+userUrl);

System.out.println("encodedUrl : "+encodedUrl);
System.out.println("decodedUrl : "+decodedUrl);

}
}


Friday, April 24, 2009

Java: Get Day of Date (dd/mm/yyyy).

This is a simple java program to get complete date information of a Date in String as "dd/MM/yyyy". Here you can get other information as well like Month, Day, Year etc.

Customized Date and Time Formats
Pattern Output
dd MMMM yyyy EEEE 24 April 2009 Friday
dd.MM.yy 24.04.09
yyyy.MM.dd G 'at' hh:mm:ss z 2009.04.09 AD at 06:15:55 PDT
EEE, MMM d, ''yy Thu, Apr 9, '09
h:mm a 6:15 PM
H:mm:ss:SSS 18:15:55:624
K:mm a,z 6:15 PM,PDT
yyyy.MMMM.dd GGG hh:mm aaa 2009.April.09 AD 06:15 PM



Date Format Pattern Syntax
Symbol Meaning Presentation Example
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Fri
EEEE day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '



For example in below code if you pass : "24/04/2009"
Output : Date is : 24 April 2009 Friday



/* GetDay.java */

import java.util.Date;
import java.text.SimpleDateFormat;

public class GetDay
{
public static void main(String[] args) throws Exception
{
String strDate = "24/04/2009";//pass your Date here

SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf1.parse(strDate);

SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMMM yyyy EEEE");

System.out.println("Date is : " + sdf2.format(date));
}
}

Sunday, April 19, 2009

DBMS: Remove Duplicate Entries from Database Table in Oracel / MS SQl

Delete Duplicate rows from database tables


Method 1.


This is simple method to remove duplicate entries from database tables. You can use it in oracle as well as MS SQL. Duplicate entries in aspect of one column or more than one column. Here in this query 'id' can be primary key or any other unique data, which identifies each row uniquely.

Note : I tested this query it works good, its very simple and easy way to delete duplicate rows from tables.

DELETE
FROM TableName
WHERE id NOT IN
( SELECT MAX(id)
FROM TableName
GROUP BY DuplicateColumName1, DuplicateColumName2)

Method 2.


This is Another simple method to remove duplicate entries from database tables. Works well with both Oracle and MS SQL.

Step 1: Move the non duplicates (unique rows) into a temporary table

Oracle Method to move non duplicates rows into new table from old table

CREATE TABLE NewTable AS
SELECT * FROM OldTable
WHERE 1
GROUP BY DuplicateColumName1, DuplicateColumName2

MS SQL Method to move non duplicates rows into new table from old table

SELECT * INTO NewTable
FROM OldTable
WHERE 1
GROUP BY DuplicateColumName1, DuplicateColumName2


Step 2: Delete old table.

We no longer need the table with all the duplicate entries, so drop it!

DROP TABLE OldTable

Step 3: Rename the New Table to the name of the Old Table

Oracle Method to Rename tables

RENAME TABLE NewTable TO OldTable

MS SQL Method to Rename tables

ALTER TABLE OldTable RENAME TO NewTABLE

Thursday, April 16, 2009

Java IO: Simple Java Program To Write Text File

Here is the simple java code to write text file.You need to import java.io package...
Used File, FileWriter & BufferedWriter. Simply copy paste the below code and run the code.




/* here is the complete code for WriteFile.java */


import java.io.*;

public class WriteFile
{
public static void main(String[] args)
{
//name of the file, it takes default path ie. current directory
String TextFileToWrite = "MyFile.txt";

try
{
File file=new File(TextFileToWrite);
FileWriter fw =new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

for(int line = 0 ; line <= 10 ; line ++)
{
bw.write("this is line " + line );
bw.newLine();
bw.flush();//flushing
}

bw.close();//closeing BufferedWriter

System.out.println("File Written sucessfully!!!");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
}

Monday, April 13, 2009

Javascript : Dynamic Dragable and Popup Div

Simple Dragable Div


<HTML>
<HEAD>
<TITLE>Dragable Div</TITLE>
<script type="text/javascript">

function agent(v)
{
return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0));
}
function xy(e,v)
{
return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX));
}

function dragOBJ(d,e)
{

function drag(e)
{
if(!stop)
{
d.style.top=(tX=xy(e,1)+oY-eY+'px');
d.style.left=(tY=xy(e)+oX-eX+'px');
}
}

var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop;

document.onmousemove=drag;
document.onmouseup=function()
{
stop=1;
document.onmousemove='';
document.onmouseup='';
};
}
</script>
</HEAD>

<BODY>

<div style="position: fixed; width: 500px; top: 150px; left: 250px; cursor: move;" onmousedown="dragOBJ(this,event); return false;">
<TABLE border = "1" width="30%">
<TR>
<TD colspan="2">This is Dragable Div</TD>
</TR>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR>
<TD>C</TD>
<TD>D</TD>
</TR>
<TR>
<TD>E</TD>
<TD>F</TD>
</TR>
</div>

</BODY>
</HTML>

Simple Popup Dragable Div


<HTML>
<HEAD>
<TITLE>Popup Dragable Div</TITLE>

<style>
/*intially hide div, show only on click*/
.parentDisable
{
z-index: 999;
width: auto;
height: auto;
position: absolute;
top: 0;
left: 0;
display: none;
background-color: #fff;
color: #aaa;
}
</style>

<script type="text/javascript">

//used for draging div
function agent(v)
{
return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0));
}
function xy(e,v)
{
return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX));
}

function dragOBJ(d,e)
{

function drag(e)
{
if(!stop)
{
d.style.top=(tX=xy(e,1)+oY-eY+'px');
d.style.left=(tY=xy(e)+oX-eX+'px');
}
}

var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop;

document.onmousemove=drag;
document.onmouseup=function()
{
stop=1;
document.onmousemove='';
document.onmouseup='';
};
}

//used for pop-up div
function pop(div)
{
document.getElementById(div).style.display='block';
return false
}
function hide(div)
{
document.getElementById(div).style.display='none';
return false
}
</script>
</HEAD>

<BODY>

<a href='#' onClick="return pop('myDiv')">Click Here</a> to popup div

<div style="position: fixed; width: 500px; top: 150px; left: 250px; cursor: move;" onmousedown="dragOBJ(this,event); return false;">
<div id='myDiv' class='parentDisable'>
<TABLE border = "1" width="30%">
<TR>
<TD colspan="2" align="right"><a href="#" onClick="return hide('myDiv')">Close</a></TD>
</TR>
<TR>
<TD>A</TD>
<TD>B</TD>
</TR>
<TR>
<TD>C</TD>
<TD>D</TD>
</TR>
<TR>
<TD>E</TD>
<TD>F</TD>
</TR>
</div>
</div>

</BODY>
</HTML>


Note : I tested this code with Mozilla FireFox, Google Chrome, Safari and Opera its working fine. But its not working with IE 8 and its higher version. Hopefully will come up with solution soon.

Sunday, April 12, 2009

Java : JDBC Connection codes in Oracle and MS SQL

Oracle Connection



/* Here is complete code for OracleConnection.java */

import java.sql.*;

public class OracleConnection
{
public static void main(String[] args)
{
//connection
Connection con=null;
ResultSet rs=null;
Statement stmt=null;

try
{
Class.forName("oracle.jdbc.driver.OracleDriver"); //Step 1: Loading Drivers

con = DriverManager.getConnection("jdbc:oracle:thin:@10.10.10.10:8080:vas","username","password"); //Step 2: Making Connection

stmt = con.createStatement(); //Step 3: Creating JDBC Statement

String query = "Select * from EMPLOYEE";

rs = stmt.executeQuery(query); //Step 4: Execute the Ststement

while (rs.next()) //Step 5: Looping through the ResultSet
{
System.out.println(rs.getString(1)+""+rs.getString(2));
}

stmt.close(); //step 6: Close the Connection and Statement
con.close();
rs=null;
stmt=null;
con=null;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}

MS SQL Connection




/* Here is complete code for MSSQLConnection.java */

import java.sql.*;

public class MSSQLConnection
{
public static void main(String[] args)
{
//connection
Connection con=null;
ResultSet rs=null;
Statement stmt=null;

try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //Step 1: Loading Drivers

con = DriverManager.getConnection("jdbc:sqlserver://10.10.10.10:8080;databaseName=DBNAME;user=scott;password=tiger"); //Step 2: Making Connection

stmt = con.createStatement(); //Step 3: Creating JDBC Statement

String query = "Select * from EMPLOYEE";

rs = stmt.executeQuery(query); //Step 4: Execute the Ststement

while (rs.next()) //Step 5: Looping through the ResultSet
{
System.out.println(rs.getString(1)+""+rs.getString(2));
}

stmt.close(); //step 6: Close the Connection and Statement
con.close();
rs=null;
stmt=null;
con=null;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}

DBMS : Simple method to create duplicate tables in Oracle and MS SQL

Oracle



1. Creating duplicate table with data in Oracle

Here New Table is exact replica of old table with same columns, same datatype with same data

create table new_table as
select * from old_table

2. Creating duplicate table with no data in oracle, only structure is copied

This is simple method to create New blank Table with same structure as old table. Just provide a false condition in where clause which will never be true

create table new_table as
select * from old_table
where ( any_column = 'false condition' )



MS SQL



1. Creating duplicate table with data in MS SQL

Similar to oracle here also new table is exact replica of old table with all data.

select * into new_table
from old_table

2. Creating duplicate table structure in MS SQL

Here also only table structure is copied with no data, just provide a false condition in where clause which will never be true.

select * into new_table
from old_table
where ( any_column = 'false_condition' )

Monday, March 30, 2009

Java : Sorting User Objects using Comparable / Comparator in Ascending or Descending order

Comparable



java.lang.Comparable

  • int objOne.compareTo(objTwo)

  • Returns
    negative if objOne < objTwo
    zero if objOne == objTwo
    positive if objOne > objTwo

  • You must modify the class whose
    instances you want to sort.

  • Only one sort sequence can be created

  • Implemented frequently in the API by:
    String, Wrapper classes, Date, Calendar...



//Complete code for SortingObject.java using Comparable


import java.util.*;

class Employee implements Comparable<Employee>//using Comparable
{
private Integer empId;
private String name;

Employee(Integer empId,String name)
{
this.empId=empId;
this.name=name;
}

public String toString()
{
return "ID: "+empId+" Name: "+name+"\n";
}

public int compareTo(Employee e)
{

return empId.compareTo(e.empId);//Sorting in Ascending order of empId
//return e.empId.compareTo(empId);//Sorting in Descending order of empId
//return name.compareTo(e.name);//Sorting in Ascending order of name
//return e.name.compareTo(name);//Sorting in Descending order of name


}
}

public class SortingObject
{
public static void main(String[] args)
{
ArrayList<Employee> employeeArray=new ArrayList<Employee>();

employeeArray.add(new Employee(11,"Ram"));
employeeArray.add(new Employee(44,"Amol"));
employeeArray.add(new Employee(9,"Kanchan"));
employeeArray.add(new Employee(22,"Madan"));
employeeArray.add(new Employee(13,"Ashwini"));

System.out.println("Before Sorting.....");
System.out.println(employeeArray);

Collections.sort(employeeArray);

System.out.println("After Sorting.....");
System.out.println(employeeArray);
}
}//end



Comparator



java.util.Comparator

  • int compare(objOne, objTwo)

  • Returns
    negative if objOne < objTwo
    zero if objOne == objTwo
    positive if objOne > objTwo

  • You build a class separate from the class whose instances you
    want to sort.

  • Many sort sequences can be created

  • Meant to be implemented to sort instances of third-party
    classes.




//Complete code for SortingObject.java using Comparator


import java.util.*;

class Employee
{
private Integer empId;
private String name;

Employee(Integer empId,String name)
{
this.empId=empId;
this.name=name;
}

public String getName()
{
return name;
}

public Integer getEmpId()
{
return empId;
}

public String toString()
{
return "ID: "+empId+" Name: "+name+"\n";
}
}

class EmployeeComparator implements Comparator<Employee>//using Comparator
{
public int compare(Employee a,Employee b)
{
return a.getEmpId().compareTo(b.getEmpId());//Sorting in Ascending order of empId
//return b.getEmpId().compareTo(a.getEmpId());//Sorting in Descending order of empId
//return a.getName().compareTo(b.getName());//Sorting in Ascending order of name
//return b.getName().compareTo(a.getName());//Sorting in Descending order of name
}
}

public class SortingObject
{
public static void main(String[] args)
{
ArrayList<Employee> employeeArray=new ArrayList<Employee>();

employeeArray.add(new Employee(11,"Ram"));
employeeArray.add(new Employee(44,"Amol"));
employeeArray.add(new Employee(9,"Kanchan"));
employeeArray.add(new Employee(22,"Madan"));
employeeArray.add(new Employee(13,"Ashwini"));

System.out.println("Before Sorting.....");
System.out.println(employeeArray);

EmployeeComparator empComp = new EmployeeComparator();

Collections.sort(employeeArray,empComp);

System.out.println("After Sorting.....");
System.out.println(employeeArray);
}
}//end

Java : Simple Example of PreparedStatement

Prepared statements are the ability to set up a statement once, and then execute it many times with different parameters. They are designed to replace building ad hoc query strings, and do so in a more secure and efficient manner. A typical prepared statement would look something like:

SELECT * FROM Employee WHERE emp_id = ?

The '?' is what is a called a placeholder. When you execute the above query, you would need to supply the value for it, which would replace the '?' in the query bove.

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency.

//code for PreparedStatementDemo.java

import java.sql.*;
public class PreparedStatementDemo
{
public static void main(String[] args) throws Exception
{
Connection con;

PreparedStatement ps;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Loading Drivers

con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Making Connection

ps=con.prepareStatement("SELECT * FROM Employee where emp_id=?");//this is prepare statement
//observe the '?'

ps.setInt(1,11);//we can also use setString("String"); for checking String

ResultSet rset=ps.executeQuery();//Execute the Prepared Statement

while(rset.next())//Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}

ps.close();//Closeing Connection and PreparedStatement
con.close();
}
}

Java : Calling a Stored Procedure in a Database

Simple program for calling a stored procedure in a oracle database

In this example we are using both IN and OUT parameters, Simply passing two IN parameters and getting Addition as OUT parameter ie a = b + c.

//Here is complete tested code for Procedure.java

import java.sql.*;
public class Procedure
{
public static void main(String[] args) throws Exception
{
Connection con;

CallableStatement cs;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:odbc:oracledsn","scott","tiger");//Step 2: Making Connection

cs=con.prepareCall("{call AddNumbers(?,?,?)}");//Calling procedure

cs.registerOutParameter(1,Types.INTEGER);//Registering 1st parameter
// Register the type of the OUT parameter

//2nd parameter
cs.setInt(2,15);//here values can also be taken as command line argument

//3rd parameter
cs.setInt(3,20);

// Execute the stored procedure and retrieve the OUT value
cs.execute();

System.out.println(cs.getInt(1));//output as 35 ie 15+20
}
}
//end




This is How Procedure is created in oracle


create or replace procedure AddNumbers(a out number, b in number, c in number)
as
begin
a:=b+c;
end AddNumbers;

Java : Java Database Connectivity (JDBC), Explained All four types with simple example

There are four types of JDBC drivers explained with simple examples using oracle database:

Type 1 : JDBC-ODBC bridge plus ODBC driver.

This driver translates JDBC method calls into ODBC function calls.
The Bridge implements Jdbc for any database for which an Odbc driver is available.

/********Code for Type1.java**********/

import java.sql.*;
public class Type1
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:odbc:madan","scott","tiger");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "SELECT * FROM Employee";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

Type 2 : Native-API, partly Java driver.

Type 2 drivers use the Java Native Interface (JNI) to make calls to a local
database library API. This driver converts the JDBC calls into a database
specific call for databases such as SQL, ORACLE etc.

Note : to set path

set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes12.jar

/********Code for Type2.java**********/

import java.sql.*;
public class Type2
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:oracle:oci8:@madan","scott","tiger");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "SELECT * FROM Employee";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}

Type 3 : JDBC-Net, pure Java driver.

Type 3 drivers are pure Java drivers that uses a proprietary network protocol to
communicate with JDBC middleware on the server.Its requests are passed through the
network to the middle-tier server. The middle-tier then translates the request to the
database. The middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.

Type 4 : Native-protocol, pure Java driver.


Type 4 drivers communicates directly with the database engine rather than through
middleware or a native library, they are usually the fastest JDBC drivers available.
This driver directly converts the java statements to SQL statements.

Note : to set path

set Classpath=%Classpath%;.;D:\oracle\ora92\jdbc\lib\Classes111.jar

/********Code for Type4.java**********/


import java.sql.*;
public class Type4
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stat;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//Step 1: Loading Drivers

con=DriverManager.getConnection("jdbc:oracle:thin:@madan:1521:oracle9","scott","tiger");//Step 2: Making Connection

stat=con.createStatement();//Step 3: Creating JDBC Statement

String query = "SELECT * FROM Employee";

ResultSet rset=stat.executeQuery(query);//Step 4: Execute the Ststement

while(rset.next())//Step 5: Looping through the ResultSet
{
System.out.println(rset.getInt(1)+" "+rset.getString(2));
}
stat.close();//step 6: Close the Connection and Statement
con.close();
}
}