Tuesday, February 26, 2013

TreeMap in Java 6 and java 7


TreeMap Class in Java

          In this post I am going to explain about some interesting difference between TreeMap class in Java 6 and Java 7 Collections. Before we are moving to TreeMap class we should know about the Map interface in Java Collection.

Map :
  1. If we want to represent a group of objects as key-value pairs then we should go for Map in.
  2. Both keys and values are objects in Map.
  3. Duplicate keys are not allowed but values can be duplicated.
  4. There is no relationship between Collection (for group of individual objects) and Map (for group of key-value pairs).
  5. Each key-value pair is called as Entry.


  
   6. There are two main Classes which is used often in our java program
       i) HashMap   ii) TreeMap

Here I am going to explain about TreeMap Class.

TreeMap:
  1. A class which implements the Sorted Map Interface.
  2. TreeMap implements the RED-BLACK Tree data structure concepts
  3. Insertion order is not preserved, because the all the entries are inserted based on some sorting order of keys.
  4. If we are depending on default natural ordering then the keys should be Homogeneous and Comparable. Otherwise we will get the ClassCastException.  Example :
              Case 1: (If Key doesn’t implement the comparable Interface)

              Output :

              Case 2: (If Map keys are not Homogeneous )

               Output :

  5.       If we are defining our own Sorting order using Comparator then the keys need not to be as
         homogeneous and comparable.
  6.       There are no restrictions on values they can be Heterogeneous and non -comparable.
  7.       Duplicate keys are not allowed but duplicate values are allowed. 

Comparison of TreeMap in Java 6 and Java 7 (based on Null acceptance)
Java 6
  1.       Insert an Entry with null key in empty TreeMap is allowed. But after inserting this entry if we 
         are trying to insert any other Entry we will get NullPointerException.(i.e TreeMap allows Null 
         key only once if it is an empty TreeMap)

  2.       Insert an Entry with null key in non-empty TreeMap we will get NullPointerException.

  3.       In TreeMap there are no restrictions on NULL values. We can use NULL values any no of 
         times in Map.

              Example :
            Output :

Java 7 

         1.      Here TreeMap shouldn’t allow NULL keys at any situation. If we are trying to insert the NULL keys we will get NullPointerException.

               Example :

              Output :
    
             

Reason : 

·                    In Java 7 The TreeMap class put method having the following line
   
 - compare(key, key); // type (and possibly null) check
       
      The above line is used to check the NULL and Type of Keys, But this line is not available in 
      Java 6 TreeMap Class.

Monday, February 18, 2013

Immutable Class



Immutable class : A class whose contents can not be changed once created.
Immutable object :  An object whose state can not be changed once constructed.

To create an immutable class following steps should be followed:
  1. Create class as a final.
  2. Make all the members of the class as private and final.
  3. Set the values of members using constructor or in static block only.
  4. Don’t provide any methods that can change the state of the object in any way (i.e not only setter methods, but also any method which can change the state).
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.

E.g.
public final class Person {
      private final String name;
      private final int age;
     
      public Person (String name,  int age) {
            this.name = name;
            this.age = age;
      }
      public int getAge() {
            return age;
      }
      public String getName() {
            return name;
      }
     
}

Immutable classes in java are :  
All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double,  BigInteger

Note  : Immutable objects are automatically thread-safe. Because the state of the immutable objects can not be changed once they are created.


Friday, February 1, 2013

JSP Custom Tag


Introduction:
A custom tag is a user-defined JSP language element. If a JSP page containing a custom tag that is translated into a servlet first,and then the tag is converted to operations on a tag handler class. The web container then invokes these operations at the time of JSP page’s servlet is executed.

Steps to create a custom tag:

  • Create a tag handler file. This file contains the tag handler class that will be executed when the JSP processor encounters your custom tag on a JSP page.

  • Create a tag library descriptor (TLD) file. The tag library descriptor file is an XML file that tells the JSP processor where to find the tag handler class once it encounters your custom tag on a JSP page.

  • We have to include the taglibrary directive in jsp page.

  • Include the following specifications in web.xml to make your custom tags available in a JSP's Page.

<taglib>                      = Root tag.
<taglib-uri>               = uri identifying a Tag Library.
<taglib-location>      = location, as a resource, where the TLD file  
                                          can be found.
Types of Custom Tags

  • Empty tags: Refer to the custom tags that do not have any attribute or body. The following code snippet shows an empty custom tag:
                                                <td:welcome />
  • Tags with attributes: Refer to custom tags for which you can define attributes to customize the behavior of the custom tag. The following code snippet shows a custom tag with an attribute color:
                         <td: welcome color=”blue”></td:welcome>
  • Tags with a body: Refer to the custom tag within which you can define nested custom tags, scripting elements, actions, HTML text,   and JSP directives. The following code snippet shows a custom tag that contains a JSP scripting element as its body:
     <td: welcome>
                   The Current Date is : <%=today_date%>
           </td:welcome>


Sample Code
Tag Handler Classes (defines behavior of the tag)
CurrentDate.java

/**
 *    Created on : Jan 29, 2013, 12:26:45 PM
 *    @author Hariharan Selvarajan
 *    This the tag handler class for custom Empty Tag.
 */

package com.customtags;

import java.util.Calendar;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class CurrentDate extends TagSupport
{
    /**
     * This is an example class for     */
   
    @Override
    public int doStartTag()
    {
        try
        {
            JspWriter out = pageContext.getOut();
            Calendar now = Calendar.getInstance();
            //Get the current date.
            out.println("<center><table><tr><td>"+
                    Calendar.getInstance().get(Calendar.DATE)+"/"+
                    (Calendar.getInstance().get(Calendar.MONTH)+1)+"/"+
                    Calendar.getInstance().get(Calendar.YEAR)+
                    "</td></tr></table></center>");
        }


       catch (Exception e)
        {
            System.out.println("Exception in Custom Tags");
        }
        return (SKIP_BODY);
    }

    @Override
    public int doEndTag()
    {
        return EVAL_PAGE;
    }
}


Tag_Attribute.java

/**
 *    Created on : Jan 29, 2013, 12:50:18 PM
 *    @author Hariharan
 *    This the tag handler class for custom tag with attributes type.
 */

package com.customtags;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.*;

public class Tag_Attribute extends TagSupport
{
    //Variables corresponding to attributes.

    private String bgcolor;
    private String color;
    private String name;
    private String width;

    public String getBgcolor()
    {
        return bgcolor;
    }
    public void setBgcolor(String bgcolor)
    {
        this.bgcolor = bgcolor;
    }

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

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }

    public String getWidth()
    {
        return width;
    }
    public void setWidth(String width)
    {
        this.width = width;
    }

    //Welcome Notification.
    @Override
    public int doStartTag()
    {
        JspWriter out = pageContext.getOut();
        String align="center";
        final int BORDER_STYLE =1;
        try
        {
              out.println("<center><table border="+BORDER_STYLE+"  
                                      bgcolor="+bgcolor+">");
              out.println("<tr><td width="+300+" align="+align+"
                                        width="+70+"><font color="+color+"> Welcome to "+
                                        getName()+"</font>"+"</td></tr><table></center>");
        }
        catch (Exception ex)
        {
            System.out.println("Custom tag with attribute has error");
        }
        return (SKIP_BODY);
    }
}


Tag_Body.java

/**
 * Created on : Jan 29, 2013, 01:27:46 PM
 * @author Hariharan Selvarajan
*
 * This the tag handler class for custom tag with body type.
 *  Display the elements of collection in HTML table format.
 */

package com.customtags;

import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class Tag_Body extends BodyTagSupport
{
    //Variables corresponding to attributes.
    private Iterator iterator;
    private Collection collection;

    public Collection getCollection()
    {
        return collection;
    }
    public void setCollection(Collection collection)
    {
        this.collection = collection;
    }

    @Override
    public int doStartTag()
    {
        if (getCollection() == null)
        {
            System.out.println("No collection with name "
                    + getCollection()
                    + " found");
        }
        iterator = getCollection().iterator();
        if (iterator.hasNext())
        {
            pageContext.setAttribute("item", iterator.next());
            return EVAL_BODY_INCLUDE;
        }                                                                                      
        else
        {
            return SKIP_BODY;
        }

    }
    //called after the body content is evaluated
    @Override
    public int doAfterBody()
    {
        {
            if (iterator.hasNext())
            {
                pageContext.setAttribute("item", iterator.next());
                return EVAL_BODY_AGAIN;
            }
            else
            {
                return SKIP_BODY;
            }

        }

    }
}



Tag Library Descriptor
customtag.tld

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>taglib-none</short-name>
    <uri>/WEB-INF/tlds/customtag</uri>
    <tag>
        <name>currentDate</name>
        <tag-class>com.customtags.CurrentDate</tag-class>
        <body-content>EMPTY</body-content>
    </tag>
    <tag>
        <name>tag_Attribute</name>
        <tag-class>com.customtags.Tag_Attribute</tag-class>
        <body-content>EMPTY</body-content>
        <attribute>
            <name>bgcolor</name>
            <required>true</required>
      <!-- bgcolor is required -->
        </attribute>
        <attribute>
            <name>width</name>
        </attribute>
        <attribute>
            <name>color</name>
            <required>false</required>
      <!-- color is required -->
        </attribute>
        <attribute>
            <name>name</name>
            <required>true</required>
      <!-- name is required -->
        </attribute>
    </tag>
    <tag>
        <name>tag_Body</name>
        <tag-class>com.customtags.Tag_Body</tag-class>
        <body-content>JSP</body-content>
        <attribute>
            <name>collection</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
       <!-- collection is required -->
        </attribute>
    </tag>
</taglib>


customtags.jsp (Here we are going to use the custom tag)

<%--
    Created on : Jan 29, 2013, 02:16:37 PM
    Author     : Hariharan Selvarajan
    Description: Custom Tags Creation
--%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<%@page import="javax.servlet.jsp.PageContext"contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/tlds/taglib-none.tld" prefix="taglib"%>
<html>
    <head>
      <meta http-equiv="Content-Type"content="text/html;charset=UTF-8">
      <title>Page</title>
    </head>
    <body>
        <h1>
            <p align="right"> <taglib:currentDate/> </p>
        </h1>
        <br/>  <br/>
        <taglib:tag_Attribute name="Custom Tag Demo" width="300" bgcolor="BROWN" color="White"/>
        <br/>     <br/>
        <%
                    java.util.Vector vector = new java.util.Vector();
                    vector.addElement("Prakash");
                    vector.addElement("Uvaraj");
                    vector.addElement("Selvam");
                    vector.addElement("Ragaven");
                    vector.addElement("Kannan");
        %>
        <table border="1">
            <taglib:tag_Body collection="<%=vector%>">
                <tr>
                    <td align="center">Welcome Mr.
                                       <%=pageContext.getAttribute("item")%></td>
                </tr>
            </taglib:tag_Body>
        </table>
        <taglib:forwardAction action="index.jsp"/>
    </body>
</html>


Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <taglib>
        <taglib-uri>/taglib-none.tld</taglib-uri>
        <taglib-location>/WEB-INF/tlds/customtag.tld</taglib-location>
    </taglib>

    <welcome-file-list>
        <welcome-file>customtags.jsp</welcome-file>
    </welcome-file-list>

</web-app>

    OUTPUT