Saturday, November 22, 2008

Date Utility Code

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtility {

/* Add Day/Month/Year to a Date
add() is used to add values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).
*/
public static void addToDate(){
System.out.println("In the ADD Operation");
// String DATE_FORMAT = "yyyy-MM-dd";
String DATE_FORMAT = "dd-MM-yyyy"; //Refer Java DOCS for formats
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
Date d1 = new Date();
System.out.println("Todays date in Calendar Format : "+c1);
System.out.println("c1.getTime() : "+c1.getTime());
System.out.println("c1.get(Calendar.YEAR): " + c1.get(Calendar.YEAR));
System.out.println("Todays date in Date Format : "+d1);
c1.set(1999,0 ,20); //(year,month,date)
System.out.println("c1.set(1999,0 ,20) : "+c1.getTime());
c1.add(Calendar.DATE,40);
System.out.println("Date + 20 days is : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}


/*Substract Day/Month/Year to a Date
roll() is used to substract values to a Calendar object.
You specify which Calendar field is to be affected by the operation
(Calendar.YEAR, Calendar.MONTH, Calendar.DATE).

Note: To substract, simply use a negative argument.
roll() does the same thing except you specify if you want to roll up (add 1)
or roll down (substract 1) to the specified Calendar field. The operation only
affects the specified field while add() adjusts other Calendar fields.
See the following example, roll() makes january rolls to december in the same
year while add() substract the YEAR field for the correct result

*/

public static void subToDate(){
System.out.println("In the SUB Operation");
String DATE_FORMAT = "dd-MM-yyyy";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
Calendar c1 = Calendar.getInstance();
c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));

// roll down, substract 1 month
c1.roll(Calendar.MONTH, false);
System.out.println("Date roll down 1 month : " + sdf.format(c1.getTime()));

c1.set(1999, 0 , 20);
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -1);
// substract 1 month
System.out.println("Date minus 1 month : " + sdf.format(c1.getTime()));
System.out.println();
System.out.println();
}

public static void daysBetween2Dates(){
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
Calendar c2 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 0 , 20);
c2.set(1999, 0 , 22);
System.out.println("Days Between "+c1.getTime()+"\t"+ c2.getTime()+" is");
System.out.println((c2.getTime().getTime() - c1.getTime().getTime())/(24*3600*1000));
System.out.println();
System.out.println();
}

public static void daysInMonth() {
Calendar c1 = Calendar.getInstance(); //new GregorianCalendar();
c1.set(1999, 6 , 20);
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
// int days = c1.get(Calendar.DATE);
int [] daysInMonths = {31,28,31,30,31,30,31,31,30,31,30,31};
daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0;
System.out.println("Days in "+month+"th month for year "+year+" is "+ daysInMonths[c1.get(Calendar.MONTH)]);
System.out.println();
System.out.println();
}

public static void getDayofTheDate() {
Date d1 = new Date();
String day = null;
DateFormat f = new SimpleDateFormat("EEEE");
try {
day = f.format(d1);
}
catch(Exception e) {
e.printStackTrace();
}
System.out.println("The dat for "+d1+" is "+day);
System.out.println();
System.out.println();
}

public static void validateAGivenDate() {
String dt = "20011223";
String invalidDt = "20031315";
String dateformat = "yyyyMMdd";
Date dt1=null , dt2=null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
sdf.setLenient(false);
dt1 = sdf.parse(dt);
dt2 = sdf.parse(invalidDt);
System.out.println("Date is ok = " + dt1 + "(" + dt + ")");
}
catch (ParseException e) {
System.out.println(e.getMessage());
}
catch (IllegalArgumentException e) {
System.out.println("Invalid date");
}
System.out.println();
System.out.println();
}

public static void compare2Dates(){
SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.set(2000, 02, 15);
c2.set(2001, 02, 15);

System.out.print(fm.format(c1.getTime())+" is ");
if(c1.before(c2)){
System.out.println("less than "+c2.getTime());
}else if(c1.after(c2)){
System.out.println("greater than "+c2.getTime());
}else if(c1.equals(c2)){
System.out.println("is equal to "+fm.format(c2.getTime()));
}
System.out.println();
System.out.println();
}

public static boolean isLeapYear(int year){
if((year%100 != 0) || (year%400 == 0)){
return true;
}
return false;
}

public static void main(String args[]){
addToDate();
subToDate();
daysBetween2Dates(); //The "right" way would be to compute the julian day number of both dates and then do the substraction.
daysInMonth();
validateAGivenDate();
compare2Dates();
getDayofTheDate();
}

}

Read more...

Creating a Custom Exception Object



Creating a Custom Exception Object



Creating a Custom Exception Object


<%!
class NewException extends Exception
{
int value;

public String toString()
{
return "NewException " + value;
}

NewException(int v)
{
value = v;
}
}

void doWork(int value) throws NewException
{
if(value == 0){
throw new NewException(value);
}
}
%>

<%
try {
doWork(3);
doWork(0);
} catch (NewException e) {
out.println("Exception: " + e);
}
%>


Read more...

Catching an ArrayIndexOutOfBoundsException Exception



Catching an ArrayIndexOutOfBoundsException Exception


Catching an ArrayIndexOutOfBoundsException Exception


<%
try {
int array[] = new int[10];
array[100] = 100;
} catch (ArrayIndexOutOfBoundsException e) {
out.println("Array index out of bounds.");
}
%>



Read more...

AVL Tree using Java

// AvlTree class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x (unimplemented)
// boolean contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// void printTree( ) --> Print tree in sorted order
// ******************ERRORS********************************
// Throws UnderflowException as appropriate

/**
* Implements an AVL tree.
* Note that all "matching" is based on the compareTo method.
* @author Mark Allen Weiss
*/
public class AvlTree>
{
/**
* Construct the tree.
*/
public AvlTree( )
{
root = null;
}

/**
* Insert into the tree; duplicates are ignored.
* @param x the item to insert.
*/
public void insert( AnyType x )
{
root = insert( x, root );
}

/**
* Remove from the tree. Nothing is done if x is not found.
* @param x the item to remove.
*/
public void remove( AnyType x )
{
System.out.println( "Sorry, remove unimplemented" );
}

/**
* Find the smallest item in the tree.
* @return smallest item or null if empty.
*/
public AnyType findMin( )
{
if( isEmpty( ) )
throw new UnderflowException( );
return findMin( root ).element;
}

/**
* Find the largest item in the tree.
* @return the largest item of null if empty.
*/
public AnyType findMax( )
{
if( isEmpty( ) )
throw new UnderflowException( );
return findMax( root ).element;
}

/**
* Find an item in the tree.
* @param x the item to search for.
* @return true if x is found.
*/
public boolean contains( AnyType x )
{
return contains( x, root );
}

/**
* Make the tree logically empty.
*/
public void makeEmpty( )
{
root = null;
}

/**
* Test if the tree is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( )
{
return root == null;
}

/**
* Print the tree contents in sorted order.
*/
public void printTree( )
{
if( isEmpty( ) )
System.out.println( "Empty tree" );
else
printTree( root );
}

/**
* Internal method to insert into a subtree.
* @param x the item to insert.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private AvlNode insert( AnyType x, AvlNode t )
{
if( t == null )
return new AvlNode( x, null, null );

int compareResult = x.compareTo( t.element );

if( compareResult < 0 )
{
t.left = insert( x, t.left );
if( height( t.left ) - height( t.right ) == 2 )
if( x.compareTo( t.left.element ) < 0 )
t = rotateWithLeftChild( t );
else
t = doubleWithLeftChild( t );
}
else if( compareResult > 0 )
{
t.right = insert( x, t.right );
if( height( t.right ) - height( t.left ) == 2 )
if( x.compareTo( t.right.element ) > 0 )
t = rotateWithRightChild( t );
else
t = doubleWithRightChild( t );
}
else
; // Duplicate; do nothing
t.height = Math.max( height( t.left ), height( t.right ) ) + 1;
return t;
}

/**
* Internal method to find the smallest item in a subtree.
* @param t the node that roots the tree.
* @return node containing the smallest item.
*/
private AvlNode findMin( AvlNode t )
{
if( t == null )
return t;

while( t.left != null )
t = t.left;
return t;
}

/**
* Internal method to find the largest item in a subtree.
* @param t the node that roots the tree.
* @return node containing the largest item.
*/
private AvlNode findMax( AvlNode t )
{
if( t == null )
return t;

while( t.right != null )
t = t.right;
return t;
}

/**
* Internal method to find an item in a subtree.
* @param x is item to search for.
* @param t the node that roots the tree.
* @return true if x is found in subtree.
*/
private boolean contains( AnyType x, AvlNode t )
{
while( t != null )
{
int compareResult = x.compareTo( t.element );

if( compareResult < 0 )
t = t.left;
else if( compareResult > 0 )
t = t.right;
else
return true; // Match
}

return false; // No match
}

/**
* Internal method to print a subtree in sorted order.
* @param t the node that roots the tree.
*/
private void printTree( AvlNode t )
{
if( t != null )
{
printTree( t.left );
System.out.println( t.element );
printTree( t.right );
}
}

/**
* Return the height of node t, or -1, if null.
*/
private int height( AvlNode t )
{
return t == null ? -1 : t.height;
}

/**
* Rotate binary tree node with left child.
* For AVL trees, this is a single rotation for case 1.
* Update heights, then return new root.
*/
private AvlNode rotateWithLeftChild( AvlNode k2 )
{
AvlNode k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
k2.height = Math.max( height( k2.left ), height( k2.right ) ) + 1;
k1.height = Math.max( height( k1.left ), k2.height ) + 1;
return k1;
}

/**
* Rotate binary tree node with right child.
* For AVL trees, this is a single rotation for case 4.
* Update heights, then return new root.
*/
private AvlNode rotateWithRightChild( AvlNode k1 )
{
AvlNode k2 = k1.right;
k1.right = k2.left;
k2.left = k1;
k1.height = Math.max( height( k1.left ), height( k1.right ) ) + 1;
k2.height = Math.max( height( k2.right ), k1.height ) + 1;
return k2;
}

/**
* Double rotate binary tree node: first left child
* with its right child; then node k3 with new left child.
* For AVL trees, this is a double rotation for case 2.
* Update heights, then return new root.
*/
private AvlNode doubleWithLeftChild( AvlNode k3 )
{
k3.left = rotateWithRightChild( k3.left );
return rotateWithLeftChild( k3 );
}

/**
* Double rotate binary tree node: first right child
* with its left child; then node k1 with new right child.
* For AVL trees, this is a double rotation for case 3.
* Update heights, then return new root.
*/
private AvlNode doubleWithRightChild( AvlNode k1 )
{
k1.right = rotateWithLeftChild( k1.right );
return rotateWithRightChild( k1 );
}

private static class AvlNode
{
// Constructors
AvlNode( AnyType theElement )
{
this( theElement, null, null );
}

AvlNode( AnyType theElement, AvlNode lt, AvlNode rt )
{
element = theElement;
left = lt;
right = rt;
height = 0;
}

AnyType element; // The data in the node
AvlNode left; // Left child
AvlNode right; // Right child
int height; // Height
}

/** The tree root. */
private AvlNode root;


// Test program
public static void main( String [ ] args )
{
AvlTree t = new AvlTree( );
final int NUMS = 4000;
final int GAP = 37;

System.out.println( "Checking... (no more output means success)" );

for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS )
t.insert( i );

if( NUMS < 40 )
t.printTree( );
if( t.findMin( ) != 1 || t.findMax( ) != NUMS - 1 )
System.out.println( "FindMin or FindMax error!" );

for( int i = 1; i < NUMS; i++ )
if( !t.contains( i ) )
System.out.println( "Find error1!" );
}
}

Read more...

Saturday, November 15, 2008

JSP

Key Acronyms         

JSP  = JavaServer Pages
JSTL = JSP Standard Tag Library
TLD  = Tag Library Descriptor
WAR  = Web-application
 ARchive
EL = Expression Language

Page Lifecycle

1. Page Translation
2. Page Compilation
3. Load Class
4. Create Object
5. Call jspInit()
6. Call _jspService()
7. Call jspDestroy()

BASIC SYNTAX

Directive Elements (translation phase)

<%@ page ... %>                                      - <jsp:directive.page .. /> in XML
<%@ include file="filename" %>                       - <
jsp:directive.include .. /> in XML
<%@
 taglib prefix="shortName" uri="tldUniqueName" %> - xmlns:prefix="tldUniqueName" in XML

Scripting Elements

<%  ...; %> - script-let   - in XML

<%= ...  %> - expression   - in XML

<%! ...; %> - declaration  - in XML

<%-- ... --%> - comment    - in XML

${ }       - JSTL 1.0/JSP2.0

Implicit objects (note not available in declarations)

application  - ServletContext
config       - ServletConfig
exception    -
 Throwable (only for pages with page directive isErrorPage="true")
request      -
 HttpServletRequest
response     -
 HttpServletResponse
out          -
 JSPWriter
page         - Object
pageContext  - PageContext
session      -
 HttpSession (only for pages with page directive session="true")

Page Directive Attributes

autoFlush    - Boolean indicating whether buffer should flush when full (true)
buffer       - buffer size in kilobytes, e.g. "32kb"
contentType  - MIME type and character encoding of output (text/html;ISO-8859-1)
errorPage    - URL of a JSP page capable of handling errors for this page (null)
extends      - sub-class of
 javax.servlet.jsp.JspPage to use
import       - comma-separated list of packages/classes (
java.lang.*, etc..)
isErrorPage  - boolean indicating page can accept errors (false)
isThreadSafe - Boolean indicating whether page is thread-safe (true)
language     - scripting language (java)
pageEncoding - character encoding of output (ISO-8859-1)
session      -
 boolean indicating whether takes part in a session (true)

Action Elements/Tags (request processing phase)

<jsp:useBean id="beanName" class="com.classes.BeanClass" [scope="page"]/>
<
jsp:useBean id="beanName" class="com.classes.BeanClass" type="com.classes.BeanSuperClass"/>
<
jsp:useBean id="beanName" beanName="serializedName" type="com.classes.BeanSuperClass"/>
<
jsp:getProperty name="beanName" property="propertyName"/>
<
jsp:setProperty name=“beanName" property="propertyName" value="propertyValue"/>
<
jsp:setProperty name=“beanName" property="propertyName" [param="requestParamName"]/>
<
jsp:include page="relativeURL"/>
<
jsp:forward page="relativeURL"/>
<
jsp:param name="paramName" value="paramValue"/>
<
jsp:plugin/>

JSTL libraries

http://java.sun.com/jsp/jstl/core (c)

http://java.sun.com/jsp/jstl/xml (x)

http://java.sun.com/jsp/jstl/fmt (fmt)

http://java.sun.com/jsp/jstl/sql (sql)

http://java.sun.com/jsp/jstl/fn (fn)

JSTL functions (JSTL 1.1)

c:out(value)

c:param(name, value)

c:forEach(var, items, varStatus)

c:forToken

c:url

c:import(url)

 

fmt:formatNumber(value, pattern)

fmt:parseNumber

fmt:formatDate

fmt:parseDate

fmt:timeZone

fmt:setTimeZone

fmt:setLocale(value)

fmt:bundle(basename)

 

fn:contains(string, substring)

fn:containsIgnoreCase(string, substring)

fn:endsWith(string, suffix)

fn:escaleXml(string)

fn:indexOf(string, substring)

fn:join(array, separator)

fn:length(item)

fn:replace(string, before, after)

fn:split(string, separator)

fn:startsWith(string, prefix)

fn:substring(string, begin, end)

fn:substringAfter(string, substring)

fn:substringBefore(string, substring)

fn:toLowerCase(string)

fn:toUpperCase(string)

fn:trim(string)

 

sql:setDataSource(var,driver,url)

sql:query(var,datasource)

sql:update

sql:transaction(dataSource)

 

x:parse(source, var)

x:out(select)

x:transform(source, xslt)

PageContext methods

setAttribute(name, valueObject)
getAttribute(name)
setAttribute(name, valueObject, scope)
getAttribute(name, scope)
getAttributeNamesInScope(scope)
removeAttribute(name, scope)
getServletContext()
getSession()
getResponse()
getRequest()

Variable scopes

jsp:usebean  Servlet

===========  =======

page         PageContext.PAGE_SCOPE

request      PageContext.REQUEST_SCOPE

session      PageContext.SESSION_SCOPE

application  PageContext.APPLICATION_SCOPE

Custom tag interfaces

Tag          - base class for simple tags
IterationTag - adds doAfterBody() for iteration processing     (default implementation -> TagSupport)
BodyTag      - adds doInitBody() for handling tags with bodies (default implementation -> BodyTagSupport)

Tag methods (in order of execution)

setPageContext() - called by the container
setParent()      - called by the container
setXXXXXX()      - called for each attribute
doStartTag()     - returns either EVAL_BODY_INCLUDE or SKIP_BODY (or EVAL_BODY_BUFFERED for BodyTag)
setBodyContent() - called by the container (BodyTag only if EVAL_BODY_BUFFERED)
doInitBody()     - return void             (BodyTag only if EVAL_BODY_BUFFERED)
doAfterBody()    - returns either EVAL_BODY_AGAIN or SKIP_BODY (IterationTag and BodyTag)
doEndTag()       - returns either EVAL_PAGE or SKIP_PAGE
release()        - called when tag handler no longer required

 

doStart

doAfterBody

doEndTag

EVAL_BODY_INCLUDE

All

 

 

EVAL_BODY_BUFFERED

BodyTag

 

 

EVAL_BODY_AGAIN

 

Iteration

 

SKIP_BODY

All

Iteration

 

EVAL_PAGE

 

 

All

SKIP_PAGE

 

 

All

Expression Language - Literals

true, false, 5, -5, 5.5, 5.5E5, "string", 'string', null

Expression Language - Operators

+,-,*,/,%,==,!,!=,<,>,<=,>=,&&,||,(,)
condition ?
 ifTrue : ifFalse
empty set

Expression Language - Equivalent JSP expressions

{$list[1]}               == <%= list.elementAt(1) %>

{$map.name}              == <%= map.get("name") %>

{$map['name']}           == <%= map.get("name") %>

{$map[name]}             == <%= map.get(pageContext.findAttribute("name")) %>

{$bean.property}         == <%= bean.getProperty() %>

 

{$pageContext.response}  == <%= pageContext.getResponse() %>

{$pageContext.session}   == <%= pageContext.getSession() %>

{$pageContext.context}   == <%= pageContext.getServletContext() %>

{$pageContext.request.requestURI} == <%= pageContext.getRequest().getRequestURI() %>

 

{$param.name}            == <%= request.getParameter("name") %>

{$paramValues.name}      == <%= request.getParameterValues("name") %>

{$header.name}           == <%= request.getHeader("name") %>

{$headerValues.name}     == <%= request.getHeaderValues("name") %>

 

{$pageScope.cart.count}  == <%= pageContext.getAttribute("cart", PageContext.PAGE_SCOPE).getCount() %>

{$requestScope.cart}     == <%= pageContext.getAttribute("cart", PageContext.REQUEST_SCOPE) %>

{$sessionScope.cart}     == <%= pageContext.getAttribute("cart", PageContext.SESSION_SCOPE) %>

{$applicationScope.cart} == <%= pageContext.getAttribute("cart", PageContext.APPLICATION_SCOPE) %>

 

{$mytl:myfn()}           - calls the myfn() function of the mytl tag library

 

EL functions are code as public static methods and identified using the function element of the TLD.

Tag Library Descriptor (META-INF/taglib.tld)

  • taglib
    • short-name
    • [display-name]
    • [description]
    • [uri] - if implicit taglib URI indirection is used
    • tlib-version
    • jsp-version
    • tag*
      • name
      • [display-name]
      • [description]
      • tag-class   - implementation of Tag
      • [tei-class] - implementation of TagExtraInfo
      • [body-content] - { empty | JSP | tagdependent }
      • [variable]*
      • [attribute]*
        • name
        • [description]
        • [required]    - { yes | no | true | false }
        • [rtexprvalue] - { yes | no | true | false } request time expressions
        • [type]        - request time expression type (default java.lang.String)
      • [example]
    • [function]*
      • name
      • [display-name]
      • [description]
      • function-class
      • function-signature
    • [listener]

WAR structure

/WEB-INF/web.xml
/WEB-INF/classes/
/WEB-INF/lib/

Read more...

  © Blogger templates Newspaper III by Ourblogtemplates.com 2008

Back to TOP