Friday, September 25, 2009

Mandatory field Marking with Custom Tags..

In a web-page’s form there always exist some mandatory fields.

We alert the end-user with a marking (*) along the side of the input fields.

Usually we tend to write labels in HTML like this in all the pages


<span >*</span>


When developing with JSP we can encapsulate this label / mark in a JSTL custom taglib and bring it in the page with our own tags.

JSTL encapsulates common functionality required for web-pages as tags.It provides a mechanism to extend and write our own functionalities.

What is the use of doing it that way?
  • Your code resides in a common place.
  • When there is are requirement to change the marker ( from “*” to “#” or from “red” to “green”) its easy.
  • You get exposure to write your own custom tag ...its cool..

Steps to write a marker custom tag:

  1. Write your tag handler class.
  2. Describe your tag handler class in a .tld (tag library descriptor) file
  3. Introduce the .tld file to your web application with a fancy name in web.xml

Your custom tag is ready and you can use it in your web page.


Step # 1: Write a tag handler class MandatoryTag.java
package dev.aha;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
*
* A TagHandler class to provide mandatory-marker for
* HTML forms
*
* Note: This class extends javax.servlet.jsp.tagext.TagSupport
* since it doesn't have a body else you should extend BodyTagSupport
*
* @author AhamedM
*
*/
public class MandatoryTag extends TagSupport {

private static final long serialVersionUID = 1L;

/**
* An attribute to define the color of the marker You can ignore this if not
* needed..
*/
private String color;

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

/**
* Note : We are overriding only the doStartTag() method because what we are
* developing is a empty-bodied-tag
*/
@Override
public int doStartTag() throws JspException {

JspWriter out = pageContext.getOut(); // Get the writer from pageContext
try {
if (getColor() == null getColor().equals("")) {
out.write("<span style=\"color:red\">*</span>");
} else if (color.equals("blue") color.equals("green"))
out.write("<span style=\"color:" + color + "\">*</span>");
} catch (IOException iex) {
}

/**
* We are returning SKIP_BODY as the body of this tag is empty
*/
return SKIP_BODY;
}
}


Step# 2: Describe the tag & tag handler in mytaglib.tld file



<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>Ahamed Tag Lib</shortname>
<info>My Simple Tag library</info>
<!-- A Simple tag -->
<tag>
<name>mandate</name>
<tagclass>dev.aha.MandatoryTag</tagclass>
<!--
Body content can have a value of empty: no body JSP: body that is
evaluated by container, then possibly processed by the tag
tagdependent: body is only processed by tag; JSP in body is not
evaluated.
-->
<bodycontent>empty</bodycontent>
<info> This is a simple tag to indicate mandatory fields. </info>

<!-- Optional attributes -->
<attribute>
<name>color</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>




Step#3: Introduce the mytaglib.tld in web.xml


<jsp-config>
<taglib>
<taglib-uri>AhamedSampleTld</taglib-uri>
<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>

</taglib>
</jsp-config>




That’s it…Yes..Its done…You can use this tag in your page to mark the fields..

Sample index.jsp page with our custom tag



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib uri="AhamedSampleTld" prefix="aha"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Mandatory field- Sample</title>
</head>
<body>
<form action="someUrl">
<table>
<tr>
<td><aha:mandate />PAN No.</td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="submit" value="SUBMIT" /></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>



ENJOI !!!!!

Tuesday, September 15, 2009

Simple, Safe & Synchronized

Java compiler is free to re-arrange the instructions provided by our java program in the name of optimization.

There are many cases where access to the variables can occur in an order than specified in the program.

A straight-forward example is:

A thread T has to write a value to a variable _va and then to a variable _vb, and if _vb is not dependent on _va, the compiler can reorder these write instructions.Write to _vb can happen before a write to _va.

In general instruction re-orders cannot be a problem in single-threaded programs but when it comes to multi-threaded programs, the re-orders can result in data race (inconsistent data) if not properly synchronized.

To ensure that any thread at any time gets the updated value/state of an object (updated by other threads), our program must have read/write operations that comply with happens-before relationship.

In simple, happens-before relationship guarantees that memory writes in one specific statement is visible to another specific statement.

Some of the actions that create happens-before relationship are:

* Thread.start
* Thread.join
* Synchronization

We also have certain other actions that creates happens-before relationship.

Synchronization is an action that can effectively prevent data race and state inconsistency. Synchronized Methods & Synchronized Statements are 2 ways that Java provides to implement this synchronization action.

These 2 provisions automatically establish happens-before relationship.

How synchronized method works:

Any object in java exists with an implicit/intrinsic lock. When a thread enters a synchronized method of an object it is this lock which it acquires. Other threads must wait for that lock gets released. When the synchronized method is static the implicit lock of the class is used.

Any arbitrary thread that waits for that lock will be intimated and enter the synchronized method. This synchronize action ensures that any write that happened inside the synchronized method is visible to the new thread entering the synchronized method.

How synchronized statements works:

Synchronized statements provide a more granularity over the counterpart. With this provision you can mark a set of statements as a synchronized block and at any time only one thread can enter this block. Unlike synchronized methods, the synchronized statements must specify the object that provides the implicit lock.

Examples for synchronization will follow....

Sunday, September 13, 2009

Simple scenarios with Java generics

A prominent feature added in Java 5.0 is “generics” which enables a programmer to write more type-safe code (code that is tied to specific expected type.. so that no surprises occur at run-time).
Simply..you can say that an API/ code utilizes “generics” when you see strange angle brackets i.e. <> in its method signatures/ class declarations.
Java compiler makes use of a technique called “Type Erasure” to erase the information related to type parameters so that the binary form maintains compatibility with old API (before generics)
You can see that collection framework in Java 5.0 heavily utilizes “generics”
Listed are the simple scenarios where we use generics in day-to-day programming
Scenario#1 :
Declare variables of generic types and instantiate generic type classes (like ArrayList,HashMap,TreeSet,Iterator)

Example#1:
List<String> names = new ArrayList<String>();
/* This guarantees that the items in “names” are always instances of java.lang.String as your code expects.
This enables you to run a for loop and traverse through the list without a class casting */

Example#2:
ArrayList<Car> listForAnyCar=new ArrayList<Car>();
listForAnyCar.add(new Ferrari());
listForAnyCar.add(new Camry());

In the given list you can add any type of Car i.e any class that extends the class Car.

Scenario#2: Pass generic type collections to methods.
You can declare that a method expects generic type collections as argument.

Example#3:
public void takeOnlyListOfStrings(List<String> strings)
{
for(String astring: strings)
System.out.println(“One of the string is”+astring);
}


Example# 4:
public void updateListOfCars(List<Car> allCars)
{
allCars.add(new HondaAccord());
}

Scenario#3:
Write generic methods
A generic method means that the method declaration uses a type parameter in its signature.

Example#5:
public <U> boolean inspectTheList(U u) {
return allCars.contains(u);
}

This method intakes any object and checks if the list allCars contains the object .
This method can further improved to add some more constraints.

public <T extends Number> boolean inspectTheList(T t)
----This signature declares that method inspectTheList can take only objects of type or subtypes of Number

public <T extends Comparable> boolean inspectTheList(T t)
---This signature declares that method inspectTheList can take only objects that implements Comparable..Yes… extends in generics means extends/implements

public <T extends Comparable & Serializable> boolean inspectTheList(T t)
---This signature declares that only objects that implements Serializable AND Comparable can be passed as parameters.

Here are some points you should be aware while declaring and using generic type collections.
1. ArrayList<Car> allCar = ArrayList<HondaAccord>(); // gives compilation error
2. ArrayList<Car> allCar = ArrayList<Car>;//compiles successfully.So compiler won’t bother if this list takes HondaAccord or Ferrari but it should be a Car.

Tuesday, September 8, 2009

By the grace of ALMIGHTY ..Welcome all !!

You... Thinking Java is cool ???

I hear a BIG "Yes"..

Then we are in same page ...


Insha ALLAH I shall update this site (blog) with valuable Java contents / updates / hints that I collect from web & books in my style :)

Definitely my postings shall aid you & me in understanding & appreciating Java better...

Watch out for more...