Monday, May 9, 2011

Write a simple Java Bean

1. Startup your apache tomcat from command line - Navigate to the bin folder and run the startup.bat. Make sure Apache tomcat webserver is running by bringing up the browser and running http://localhost:8080

Note:-The configured HTTP port can be found by viewing the server.xml file in the conf directory.

2.We first need to write a Java code and then compile the java code and place the generated .class file in the appropriate package directory.

For example: - In our test example here - MyCalendar.java is placed under webapps/begjsp-ch02 directory of the apache tomcat installation.

package dates;
import java.util.*;
import java.text.SimpleDateFormat;
public class MyCalendar
{
private Date curDate;
private SimpleDateFormat sf;
private GregorianCalendar gf;


public String getCurrentDate()
{
gf = new GregorianCalendar();
curDate=gf.getTime();
sf = new SimpleDateFormat("EEE, HH:MM:SS");
return ((String) sf.format(curDate));
}
/*
public static void main (String args[])
{
MyCalendar mc = new MyCalendar();
System.out.println("SimpleFormatDate" + mc.getCurrentDate());

}
*/
}

If you notice this java code belongs to "dates" package.

3.Therefore after you have compiled the .java file, place the generated .class file under
webapps/begjsp-ch02/WEB-INF/classes/dates/ folder path.

4.Place the calling jsp code under begjsp-ch02 folder


In order to call the function getCurrentDate in the java class, it is accessed through the java bean as currentDate. Notice we removed the "get" and converted the property into first letter in "CurrentDate" as lowercase to follow the bean naming standards.

Comparable interface example

When i was compiling my class, i was getting abstract method error on the MyShopping Cart class when i was specifically typecasting the list.
public class MyShoppingCart implements Comparable

The error thrown by the Java interpretor was the following error

C:\jakarta\apache-tomcat-6.0.24\webapps\begjsp-ch02\MyShoppingCart.java:4: MyShoppingCart is not abstract and does not override abstract method compareTo(MyShoppingCart) in java.lang.Comparable
public class MyShoppingCart implements Comparable

In order to the correct the error, I made the following changes to my compareTo method implemented for the Comparable interface.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collections;
public class MyShoppingCart implements Comparable
{
private String name;
private float cost;

public MyShoppingCart()
{
name="";
cost=0.0f;
}
public MyShoppingCart(String name, float cost)
{
this.name=name;
this.cost=cost;
}

public boolean equals (Object obj)
{
if (!(obj instanceof MyShoppingCart))
{
return false;
}
MyShoppingCart sc = (MyShoppingCart)obj;
return (this.name).equals(sc.name);
}

public int hashCode()
{
return name.hashCode();
}

//public int compareTo(Object element ) <-- Incorrect code
public int compareTo(MyShoppingCart element )
{

// MyShoppingCart sc = (MyShoppingCart) element; <-- Incorrect code
MyShoppingCart sc = element;
String uname = sc.name;
return (this.name.compareTo(uname));
}


public static void main (String args[])
{
ArrayList mylist = new ArrayList ();
System.out.println("The size of mylist is " +mylist.size());

MyShoppingCart a1 = new MyShoppingCart("Dell Laptop", 1500.99f);
MyShoppingCart a2 = new MyShoppingCart("Apple IPAD", 599.99f);
MyShoppingCart a3 = new MyShoppingCart("X-box 360", 699.99f);
MyShoppingCart a4 = new MyShoppingCart("Tennis racket", 49.5f);
System.out.println("Is the list empty? " + mylist.isEmpty());
mylist.add(a1);

System.out.println("Is the list empty? " + mylist.isEmpty());
mylist.add(a2);
mylist.add(a3);
mylist.add(a4);

System.out.println("The size of mylist is " +mylist.size());
System.out.println("The index within the list for matching record Dell Laptop, 1500.99f is:" + mylist.indexOf(a1));
Iterator iter = mylist.iterator();
while (iter.hasNext())
{
MyShoppingCart m1 = (MyShoppingCart)iter.next();
System.out.println(m1.name + " " + m1.cost);
}
iter = mylist.iterator();
System.out.println("After sorting....");
Collections.sort(mylist);
while (iter.hasNext())
{
MyShoppingCart m1 = (MyShoppingCart)iter.next();
System.out.println(m1.name + " " + m1.cost);
}

}
}

Sunday, August 24, 2008

HashSets, TreeSets, Array Lists, Comparable and Comparators

import java.util.*;

//This class is used to sort a collection in descending order of age and name
//A comparator class is usually written when a programmer usually does not have access to
//source code and then he can create his own custom sort using custom Comparator class as shown in
//Person class below
class Person implements Comparator
{
String name;
int age;
public Person(String name,int age)
{
this.name=name;
this.age=age;
}
public Person()
{
name="";
age=0;
}
public int compare(Person p1,Person p2)
{
if (p2.age>p1.age) return (p2.age-p1.age);
else if (p2.age < p1.age) return (p2.age-p1.age);
else
{
return (p2.name.compareTo(p1.name));
}
}

//Implementing equals method is optional. If implemented to over-ride, make sure the result is consistent with the compare method
public boolean equals(Object o)
{
Person p2 = (Person) o;
if (p2.age>this.age) return (true);
else if (p2.age < this.age) return (false);
else
{
if (p2.name.compareTo(this.name)>= 0)
return true;
else
return false;
}
}


//Over-ride from the object class.
public String toString()
{
return ("Name=" + this.name + ", age=" + this.age);
}
}

//This class sorts a collection in ascending order of age and name and implements comparable.
class PersonComparable implements Comparable {
String name;
int age;
public PersonComparable(String name,int age)
{
this.name=name;
this.age=age;
}
public int compareTo(PersonComparable p2)
{

if (this.age>p2.age) return (this.age-p2.age);
else if (this.age < p2.age) return (this.age-p2.age);
else
{
return (this.name.compareTo(p2.name));
}
}
//Implementing equals method is optional. If implemented to over-ride, make sure the result is consistent with the compareTo method
public boolean equals(Object o)
{
PersonComparable p2 = (PersonComparable) o;
if (this.age>p2.age) return (true);
else if (this.age < p2.age) return (false);
else
{
if (this.name.compareTo(p2.name)>= 0)
return true;
else
return false;
}
}

public String toString()
{
return ("Name=" + this.name + ", age=" + this.age);
}
}

public class CollectionsTest01
{

public static void main(String args[])
{
//hashset allows duplicate and null values. This set is created with Primitive class- string
//hash sets are not ordered by default
Set hs1 = new HashSet();
System.out.println("The original size of the hashset is="+ hs1.size());
hs1.add("temp");
hs1.add(Integer.toString(1));
hs1.add(Boolean.toString(true));
hs1.add("Dushyant");
hs1.add("temp");
hs1.add(null);
System.out.println("The current size of the hashset is="+ hs1.size());
System.out.println("The String hash set is="+hs1);

//hashset allows duplicate and null values. This set is created with Custom class- Person
//hash sets are not ordered by default even if you implement the comparator or comparable interfaces.
HashSet ps1 = new HashSet ();
ps1.add(new Person("Donde Estas",35));
ps1.add(new Person("Ronnie Baron",35));
ps1.add(new Person("Google froogle",31));
ps1.add(new Person("Simple simon",24));
ps1.add(new Person("Greg Bruno",3));
ps1.add(new Person("Ronnie Baron",35));

System.out.println("Iterating through Person hash set");
Iterator it = ps1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
//When sorting a tree set pass the comparator in the the tree set constructor.
//Tree sets are sorted order sets and apply the compare method
TreeSet personTreeSet1 = new TreeSet(new Person());
personTreeSet1.add(new Person("Donde Estas",35));
personTreeSet1.add(new Person("Ronnie Baron",35));
personTreeSet1.add(new Person("Google froogle",31));
personTreeSet1.add(new Person("Simple simon",24));
personTreeSet1.add(new Person("Greg Bruno",3));
personTreeSet1.add(new Person("Ronnie Baron",35));

System.out.println("Iterating through Person Tree set");
it = personTreeSet1.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

//Creating a tree set implementing Comparable.
//Tree sets are sorted order sets and apply the comparable interface. Use the compareTo method here to sort.
TreeSet ts1 = new TreeSet ();
ts1.add(new PersonComparable("Damini",35));
ts1.add(new PersonComparable("Gamini",35));
ts1.add(new PersonComparable("Kumari",31));
ts1.add(new PersonComparable("Tsunami",24));
ts1.add(new PersonComparable("Kumari",31));
Iterator it2 = ts1.iterator();
System.out.println("The size of the tree set is="+ts1.size());
System.out.println("Iterating through PersonComparable Tree set");
while(it2.hasNext())
{
System.out.println(it2.next());
}

//Example to apply the static collections method sort and reverseOrder. These static methods only apply on lists.
//The array list is created with Comparable constructor.
ArrayList lst1= new ArrayList();
lst1.add(new PersonComparable("Raj Kapoor",36));
lst1.add(new PersonComparable("Vinod Khanna",39));
lst1.add(new PersonComparable("Dilip Kumar",36));
lst1.add(new PersonComparable("Dilip Kumar",36));
System.out.println("Display the array list before sorting="+lst1);
Collections.sort(lst1);
System.out.println(lst1);

System.out.println("Display the array list after sorting="+lst1);
Collections.sort(lst1,Collections.reverseOrder());
System.out.println("Reverse order sorted list="+lst1);

//Example to apply the static collections method sort and reverseOrder. These static methods only apply on lists.
//The array list is created with Comparator constructor when applied later. In this example Person comparator is applied
ArrayList lstPerson = new ArrayList();
lstPerson.add(new Person("Robin Hood",36));
lstPerson.add(new Person("John Peter",39));
lstPerson.add(new Person("Dwight York",36));
lstPerson.add(new Person("Kevin Pieterson",36));
Collections.sort(lstPerson,new Person());
System.out.println("Applying comparator Person to sort the list="+lstPerson);

TreeSet lst2= new TreeSet();
lst2.add(new PersonComparable("Rajarshi",36));
lst2.add(new PersonComparable("JP",39));
lst2.add(new PersonComparable("Mangesh",36));
lst2.add(new PersonComparable("JP",39));
//Collections.sort(lst2); You cannot apply this Static method on a set. It only applies on a list.
System.out.println(lst2);

ArrayList c = new ArrayList();
c.add(1);c.add(2);
c.add(3);
ArrayList al = new ArrayList(c);
System.out.println("The current size of the collection is="+ al.size());

Set set = new HashSet();
set.add("zab");
set.add("one");
set.add("two");
set.add("three");
set.add("four");
set.add("one");
set.add("abc");
set.add(Integer.toString(3));
System.out.println(set);
Set sortedSet= new TreeSet(set);
System.out.println(sortedSet);
}
}

Sunday, July 27, 2008

PipedInput Stream and PipedOutputStream

import java.io.*;
// reads numbers from input stream and compute running average
class WriteToFile extends Thread
{
private DataInputStream in;
String msg;
private FileOutputStream out;
File f1=new File("C:\\Program Files\\Java\\jdk1.5.0_14\\test\\AJP","output.txt");



public WriteToFile(InputStream i)
{
in=new DataInputStream(i);
try
{
out = new FileOutputStream(f1);
}catch(FileNotFoundException e) { e.printStackTrace();}

}
public void run()
{
String CRLF = "\n";
try {
int count;
while (true)
{

byte buffer[] = new byte[50];

count=in.read(buffer,0,50);
if (count==-1) break;
// System.out.println("Available bytes to read : " + count);
msg = new String(buffer,0,count);


if (count==-1 ||msg.equalsIgnoreCase("EOI") ) { in.close(); break;}
if (count>0 && msg.equalsIgnoreCase("EOI")==false)
{

out.write(buffer,0,count);
if (in.available()==0)
out.write(CRLF.getBytes());
}
}
out.flush();
} catch (Exception e) { e.printStackTrace();}

}

}
class ReadFromCommandLine extends Thread {
private DataOutputStream out;
private BufferedReader buf;
String msg;
public ReadFromCommandLine(OutputStream o) {
out = new DataOutputStream(o);
buf = new BufferedReader(new InputStreamReader(System.in));

}
public void run() {


try {
System.out.println("Please enter the text in multiple lines to write to a file:");
while (true)
{
msg = buf.readLine();

byte b[]=msg.getBytes();
out.write(b);
out.flush();
// System.out.println(msg);
if (msg.equalsIgnoreCase("EOI"))
{
out.close();
break;
}

}


} catch (Exception e) { e.printStackTrace();}

}

}

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

try {
PipedOutputStream inputreader =new PipedOutputStream();
PipedInputStream filewriter =new PipedInputStream(inputreader);

ReadFromCommandLine readCommandLine = new ReadFromCommandLine(inputreader);
WriteToFile writeFile = new WriteToFile(filewriter);
readCommandLine.setPriority(1);
readCommandLine.start();
writeFile.start();
} catch (IOException e) {e.printStackTrace();}
}
}

Thursday, July 24, 2008

BufferedInputStream,BufferedOutputStream,FileInputStream,FileOutputStream


import java.io.*;
class TestByteStreams{
public static void main(String args[]) throws IOException
{

File f1=new File("C:\\Program Files\\Java\\jdk1.5.0_14\\test\\AJP","BoxArray.java");

System.out.println("Path seperator=" + f1.pathSeparator);

System.out.println("seperator=" + f1.separator);

FileInputStream fInputStream = new FileInputStream(f1);
BufferedInputStream bInputStream = new BufferedInputStream(fInputStream);
byte byteInputArray [] = new byte[500];
FileOutputStream fOutputStream = new FileOutputStream (f1 + "_copy2.java");
BufferedOutputStream bOutputStream = new BufferedOutputStream(fOutputStream,1024);
int count;
while ((count = bInputStream.read(byteInputArray,0,500))>0)

{
//BufferedOutputStream data is written to file or out when the buffer size = 1024 specified in the bufferedoutputstream is reached.
bOutputStream.write(byteInputArray,0,count);

}
//Once reading is complete and byteInputArray filled size is less than 1024 buffered output stream size,
//the output will not be written unless flushed exclusively
bOutputStream.flush();

fInputStream.close();
fOutputStream.close();


/*ByteArrayOutputStream bo = new ByteArrayOutputStream();
String s1 = "Twinkle twinkle litte star";
String s2 = "How I wonder what you are";
byte b1[] = s1.getBytes();
byte b2[] = s2.getBytes();
bo.write(b1);
bo.write(b2);
bo.close();
byte b3[] = bo.toByteArray();
ByteArrayInputStream bi = new ByteArrayInputStream(b3);
int size = bi.available();
for (int i=0; i{
System.out.print((char) bi.read());
}
System.out.println();*/


}

}


Monday, July 14, 2008

Calendar Application

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class MyAdapter implements ActionListener
{

FrameCalendar fc;

public MyAdapter(FrameCalendar fc1)
{
fc=fc1;
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource()==fc.btnDisplay)
{
int month,year;
GregorianCalendar c = new GregorianCalendar();
try
{
month=Integer.parseInt(fc.tMonth.getText());
year=Integer.parseInt(fc.tYear.getText());
} catch (NumberFormatException e)
{ month=c.get(Calendar.MONTH)+1;
year=c.get(Calendar.YEAR);
}
c.set(Calendar.DATE,1);
c.set(Calendar.MONTH,month-1);
c.set(Calendar.YEAR,year);
printCalendar(c);
}
}

private void printCalendar(GregorianCalendar c)
{
String DAY_OF_WEEK[] = {"Su","Mo","Tu","We","Th","Fr","Sa"};
int monthLength[]={31,28,31,30,31,30,31,31,30,31,30,31};
int MonthArray[][]=new int[6][7];
int month,year,date;
for (int i=0;i<6;i++)
{
Arrays.fill(MonthArray[i],0);
}
c.set(Calendar.DATE,1);
date=c.get(Calendar.DATE);
month=c.get(Calendar.MONTH);
year=c.get(Calendar.YEAR);

int i;

for (i=0;i{
System.out.print(DAY_OF_WEEK[i]+"\t");
fc.ta.append(DAY_OF_WEEK[i]+"\t");
}
System.out.println();
if ((month==1) && (c.isLeapYear(year)))
monthLength[1]=29;
else
monthLength[1]=28;

for (i=1;i<=monthLength[month];i++)
{
MonthArray[c.get(Calendar.WEEK_OF_MONTH)-1][c.get(Calendar.DAY_OF_WEEK)-1]=i;
c.roll(Calendar.DATE,1);
}
for (i=0;i<6;i++)
{
System.out.println();
fc.ta.append("\n");
for (int j=0;j<7;j++)
{
if (MonthArray[i][j]==0)
{
System.out.print("\t");
fc.ta.append("\t");
}
else
{
System.out.print(MonthArray[i][j] + "\t");
fc.ta.append(MonthArray[i][j] + "\t");
}
}
}
}
}
public class FrameCalendar extends Frame
{
Frame f1;
Label l1;
Button btnDisplay;
Panel p1,p2;
TextField tMonth, tYear;
TextArea ta;

public FrameCalendar(){
f1=new Frame();
f1.setSize(400,400);
l1=new Label("Please enter Month and Year");
btnDisplay=new Button("Show");
tMonth=new TextField("Enter Month");
tYear=new TextField("Enter Year");
p1=new Panel();
p1.add(l1);
p1.add(btnDisplay);
p1.add(tMonth);
p1.add(tYear);
f1.add(p1);
p2=new Panel();
ta = new TextArea("",10,50,0);
p2.add(ta);
f1.add(p2);
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
f1.setLayout(new GridLayout(2,1));
f1.setVisible(true);
p1.setVisible(true);
p2.setVisible(true);
btnDisplay.addActionListener(new MyAdapter(this));
}

public static void main(String args[])
{
FrameCalendar fc = new FrameCalendar();
}
}

Tuesday, July 8, 2008

Wrapper classes for primitive types

Constructors
Integer (int i)
Integer(String s)

Methods to Convert primitive integer type to Integer Object
public static Integer decode(String s)
public static Integer valueOf(String s) => The string format can be number, leading 0 for octal, # or 0x for Hexadecimal
public static Integer valueOf(String s, int radix)

Methods to convert Integer Object to different primitive types
public byte byteValue()
public double doubleValue()
public float floatValue()
public int intValue()
public long longValue()
public short shortValue()

Methods for converting a String to primtive type
public int parseInt(String s)
public int parseInt(String s, int radix)

Methods for converting a primitive type to String
public static String toString(int i)
public static String toBinaryString(int i)
public static String toHexString(int i)
public static String toOctalString(int i)

Methods to compare Integer Object
public boolean equals(Object x)
public int compareTo(Integer x)

Integer.MIN_VALUE and Integer.MAX_VALUE fields to compare max and min values for a particular Object type.

This is similar for Short, byte, boolean, long, double, float.