Wednesday, May 11, 2011

Date, GregorianCalendar, SimpleDateFormat Classes Explained

import java.util.*;
import java.text.SimpleDateFormat;
public class MyCalendar
{
private Date curr_date;
private GregorianCalendar greg_targ_date;
private String display_curr_date;
private SimpleDateFormat sf;
private String msg;

public MyCalendar()
{
curr_date = new Date();
//By default instantiation of this Date returns current Date. The date returned is in a long format.
//If you would like a simplified format here is how the Date object is converted into simple text format which is of type String.
sf = new SimpleDateFormat("K:mm a, z");
display_curr_date = sf.format(curr_date);

//You can use the gregorian format Object to set Year, month, day and time specifically.
greg_targ_date = new GregorianCalendar();
greg_targ_date.set(greg_targ_date.YEAR,3000);
greg_targ_date.set(greg_targ_date.MONTH,0);
greg_targ_date.set(greg_targ_date.DATE,1);
greg_targ_date.set(greg_targ_date.AM_PM,0);
greg_targ_date.set(greg_targ_date.HOUR,0);
greg_targ_date.set(greg_targ_date.MINUTE,0);
greg_targ_date.set(greg_targ_date.SECOND,0);
}
//This function returns the current date/time converted into simple date format object.
public String getCurrentDate()
{
return (display_curr_date);
}

//This function calculates the number of days remaining from today's date/time to Year 3000 stored in targ_date
public String getMessage()
{

Date targ_date= (Date)greg_targ_date.getTime();

// Gregorian calendar Date object is converted into Date object using getTime() method.
// When getTime() method is applied on a Date object, the Date/Time is returned in milliseconds.
// Therefore (greg_targ_date.getTime()).getTime() would yield the date/time in milliseconds.
switch(targ_date.compareTo(curr_date)) // Comparing the Date object using compareTo since Date object implements Comparable Interface.
{
case 1:
long milseconds = targ_date.getTime() - curr_date.getTime(); // Difference in milliseconds between target date and current date.
long msInDay = 1000 * 60 * 60 * 24;
long daysToGo = (long) (milseconds / msInDay);
return ("The number of days to go is " + daysToGo + " from target date");
case 0:
return ("Current date equal to target date");
case -1:
default:
return ("Expired Counter");
}
}


public static void main (String args[])
{
MyCalendar mc = new MyCalendar();
System.out.println("--------------------------------------------------------------------------------");
System.out.println("Date converted into SimpleFormat (displaying time and AM/PM)=" + mc.getCurrentDate());
System.out.println("Display current date/time using Date Object=" + mc.curr_date);
System.out.println("Display current date in milliseconds=" +mc.curr_date.getTime());
System.out.println("--------------------------------------------------------------------------------");
System.out.println("Example displaying GregorianCalendar object applied getTime() method multiple times");
System.out.println("--------------------------------------------------------------------------------");
GregorianCalendar temp = new GregorianCalendar();
System.out.println("Original GregorianCalendar Object(temp)=" + temp);
System.out.println("");
System.out.println("");
System.out.println("Applying getTime() on GregorianCalendar Object yields Date Object");
System.out.println("temp.getTime()=" + temp.getTime());
System.out.println("");
System.out.println("");
System.out.println("Applying getTime() on Date Object yields Date in seconds(datatype = long)");
System.out.println("temp.getTime()).getTime()=" + (temp.getTime()).getTime());
System.out.println("--------------------------------------------------------------------------------");
//Calling the method which displays number of days from today until Year 3000 (target date)
System.out.println(mc.getMessage());
}

}
The java output is displayed below

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);
}

}
}