Thursday, November 26, 2009

JQuery Country State HTML SELECT [Dropdown] AJAX Implementation using JSON

This is the basic tutorial which will help you to start with JQuery and JSON(Java Script Object Notation) Objects. The following is the Project Structure in Netbeans; I worked in Netbeans hence soJ. In this tutorial I will start with JQuery AJAX Implementation with XML Objects,

For my convenience I have not downloaded/Installed any JQuery Javascript file in the current project, Still I am referring to the JQuery Website shared JavaScript Files. Hope it will help you from getting confused to the version of JQuery and other JS Files.
JQuery AJAX Using JSON Objects.

I know whenever we hear about AJAX Country/State Drop down example will come into our mind, So I am also referring to the same. Here whenever the User changes the Country Dropdown we will update the State associated with that Country.
In this example we have only two JSP Files,
    1. indexJSON.jsp
    2. CountryStateJSON.jsp
Hope you can Apply few style sheet to make the index.jsp as followsJ, I think the image is ext-js component, any way I kept image to give you an idea.



The state information we are responding to the client as a JSON Object as follows.
LinkedHashSet statesSet = new LinkedHashSet< HTMLOption>();
        statesSet.add(new HTMLOption("1", "Kerala"));
        statesSet.add(new HTMLOption("2","Karnataka"));
        statesSet.add(new HTMLOption("3", "Delhi"));
        System.out.println("Linked Hash Map:"+statesSet);
        out.println(statesSet);

The above Code will generate the JSON Object as follows
     [   {id:1,value:'Kerala'}, 
         {id:2,value:'Karnataka'}, 
         {id:3,value:'Delhi'}   ]
The following Line of code in JSP will help to respond the Data as a Java Script File.

     response.setContentType("text/javascript");
     response.addHeader("Content-Disposition", "attachment; filename="+ "states.js");

In the current Example I am not connecting any Database for fetching the State details; I am simply updating the State drop down with My State in India and the neighborJ.We have two drop down in Our Page with ids
1. Dropdown Country id="country"
2. Dropdown State id=" stateDD"
       Country “onchange” we are calling function loadState(), which makes an JQuery AJAX Request to the CountryStateJSON.jsp, and It is handling the response as JavaScript Object(JSON), (by using the dataType TAG we are representing it) and pass the js File to the  loadStateFromJSON Function.
       By Using JSON Object Parser It iterates and retrieve all the states from JSON and Add to the state DropDown using appendState Method.
  ClearDD Method : It will remove all the options under the stateDD.
Example.
IndexJSON.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>JSP Page>/title>
        
        
    </head>
    <body>

Hello World!

Country : State : </body> </html>


The countryState.jsp is simply receiving the countryId from request and responding a static states xml file.
CountryStateJSON.jsp

<%
       <@ page import="java.util.LinkedHashSet" >
       <@ page import="java.util.LinkedHashMap" >
       <@ page import="org.json.model.HTMLOption" >
       <%
        System.out.println("CountryID-----------"+request.getParameter("countryId"));
        response.setContentType("text/javascript");
        response.addHeader("Content-Disposition", "attachment; filename="
          + "states.js");
        LinkedHashSet statesSet = new LinkedHashSet();
        statesSet.add(new HTMLOption("1", "Kerala"));
        statesSet.add(new HTMLOption("2","Karnataka"));
        statesSet.add(new HTMLOption("3", "Delhi"));
        System.out.println("Linked Hash Map:"+statesSet);
        out.println(statesSet);
%>
HTMLOption.java

package org.json.model;

public class HTMLOption {

    String id;
    String value;

    public HTMLOption(String id, String value) {
        this.id = id;
        this.value = value;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "{id:"+id+",value:'"+value+"'}";
    }
}
NOTE: Here toString method need to implemented, and the data String should be as Key=Value (Eq: id = 1 ) and each entry shuld be separated by a Comma. For Multiple Values Please Refer HashSet Printing.

Eid Mubarak


'EID MUBARAK' 
Wishing you & your family a very happy, healthy and prosperous Eid!!



Eid Mubarak

Wednesday, November 25, 2009

JQuery Country State HTML SELECT [Dropdown] AJAX Implementation using XML.

This is the basic tutorial which will help you to start with JQuery and JSON(Java Script Object Notation) Objects. The following is the Project Structure in Netbeans; I worked in Netbeans hence soJ. In this tutorial I will start with JQuery AJAX Implementation with XML Objects,

For my convenience I have not downloaded/Installed any JQuery Javascript file in the current project, Still I am referring to the JQuery Website shared JavaScript Files. Hope it will help you from getting confused to the version of JQuery and other JS Files.
JQuery AJAX Using XML Objects.

I know whenever we hear about AJAX Country/State Drop down example will come into our mind, So I am also referring to the same. Here whenever the User changes the Country Dropdown we will update the State associated with that Country.
In this example we have only two JSP Files,
    1. index.jsp
    2. CountryState.jsp
Hope you can Apply few style sheet to make the index.jsp as followsJ, I think the image is ext-js component, any way I kept image to give you an idea.



The state information we are responding to the client as an XML File as follows.

 Kerala
 Karnataka

The following Line of code in JSP will help to respond the Data as a File.
response.setContentType("text/xml");
response.addHeader("Content-Disposition", "attachment; filename="states.xml");
In the current Example I am not connecting any Database for fetching the State details; I am simply updating the State drop down with My State in India and the neighborJ.
We have two drop down in Our Page with ids
1. Dropdown Country id="country"
2. Dropdown State id=" stateDD"
   Country “onchange” we are calling function loadState(), which makes an JQuery AJAX Request to the CountryState.jsp, and It is handling the response as XML, (by using the dataType TAG we are representing it) and pass the XML File to the  loadStatesFromXML Function.
      By Using XML Parser by JQuery It iterates and retrieve all the states from XML and Add to the state DropDown using appendState Method.


    ClearDD Method : It will remove all the options under the stateDD.


Example.
Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
        <title>JSP Page>/title>
        
        
    </head>
    <body>

Hello World!

Country : State : </body> </html>
The countryState.jsp is simply receiving the countryId from request and responding a static states xml file.
CountryState.jsp

        <%
        String countryId = request.getParameter("countryId");
        response.setContentType("text/xml");
        response.addHeader("Content-Disposition", "attachment; filename="
          + "states.xml");
        out.println("" +
                "" +
                    "Kerala" +
                    "Karnataka" +
                "");
        %>

This file can be customized according to availability of Country state data, as Database tables or Data Files. I will explain the same in JQuery Using JSON.

How to Add or Remove an Option in HTML Select using JQuery.

Here is the code for appending an Option to a State Dropdown.

JQuery Option ADD
/**
*      id :id of the option
*      state :Name of the state we are adding
*      Dropdown id is :stateDD.
**/

function appendState(id,state){
      $('#stateDD').append($("<option id='+id+' > "+ state + "</option>"));
}

JQuery Dropdown Option Remove ALL.
/**
*      method will remove all the options Under the dropdown with ID:stateDD.
**/

function clearDD(){
        $('#stateDD').find('option').remove();
}

Wednesday, November 18, 2009

Java Serialization A Complete Tutorials.

Java Serialization
    In Programming layman’s language Serialization is the process of converting an object into a sequence of bits. That is the sequence of bytes can be persisted on a storage medium like a file or a memory buffer, and it can be transmitted across networks, hence later it can be restored as the same Object by the process of de serialization .ie It is a mechanism with which you can save the state of an object by converting it to a byte stream. This process of serializing an object is also called deflating or marshalling

Object serialization provides the foundation for Java's remote method invocation (RMI) capabilities that enable Java programs that are distributed over a network to invoke each others so-called "remote methods." RMI is used frequently in distributed enterprise applications that are built with Java Enterprise Edition (Java EE).

Let’s check different Scenarios while object serializing.

1.While Serializing an Object it will recursively checks the reference objects whether they are implemented Serializable interface or Not. Means every reference of a Serializing Object should also be Serialized, Otherwise it will generate java.io.NotSerializableException.

        Example:
        class MyDetails implements Serializable{
                String name;
                int age;
        }

Important point about java.lang.Object not implementing the Serializable interface is that any class you create that extends only Object (and no other serializable classes) is not serializable unless you implement the interface yourself.

“The object to be persisted must implement the Serializable interface or inherit that implementation from its object hierarchy.”

2.We did the basic Java Serialization, Now if we need to block some fields should not be saved through Serialization, here it comes with the Java Keyword Transient.

Ex: transient private Integer age=28;
This statement declares an integer variable named age is not a part of the persistent state of the class.

You use the transient keyword to indicate to the Java virtual machine that the indicated variable is not part of the persistent state of the object. In the saving Object Time JVM will discard the transient variables. Variables that are part of the persistent state of an object must be saved when the object is archived.

Scenario Where we Use Transient:
     In system-level classes like Thread, OutputStream and its subclasses, and Socket are not serializable. Indeed, it would not make any sense if they were. For example, thread running in my JVM would be using my system's memory. Persisting it and trying to run it in your JVM would make no sense at all.

          Class MyAnimation{
                  transient Thread serialPortReader.
          }

Here the serial port reading thread will be different in different


3.Stop Serialization:

 In some scenario if we want to stop the serialization, you are thinking how. Lets see an example

          Class Person implements Serialization{
          }
        
          Class Student extends Person{
          }

Here if we need to block Student Object Serialization, How we do?

         Private void writeObject(ObjectOutputStream out) throws IOException
         {
                throw new NotSerializableException("Not today!");
         }

         private void readObject(ObjectInputStream in) throws IOException
         {
                throw new NotSerializableException("Not today!");
         }

Here once you try to serialize the Student Object It will throw NotSerializableException.

4.Versioning Serialization

 One interesting thing will come into our mind that, once we stored the Object and later the Class is being changed, then how you will manage or restore the Object.

In Java 1.1, they have introduced version number. A specific class variable, serialVersionUID (representing the Stream Unique Identifier, or SUID), may be used to specify the earliest version of the class that can be deserialized. The SUID is declared as follows:

          static final long serialVersionUID = 2L;

This particular declaration and assignment specifies that version 2 is as far back as this class can go. It is not compatible with an object written by version 1 of the class, and it cannot write a version 1 object. If it encounters a version 1 object in a stream (such as when restoring from a file), an InvalidClassException will be thrown.

Incase if we are not providing any serialVersionUID the jvm will assign a default while the object is serialized.

The following code will help us to get the SerialVersionId.

          ObjectStreamClass myObject = ObjectStreamClass.lookup(Class.forName( "MyClass" ) );
          long theSUID = myObject.getSerialVersionUID();

Hence we can check the versioned of the object and handle the InvalidClassException on Runtime.
.
Lets look a complete Example :
package serializing;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Serialize {

          /**
         * @param args
         */
         public static void main(String[] args) {
                 FileOutputStream fileOut = null;
                 ObjectOutputStream out = null;
                 try {
                         fileOut = new FileOutputStream("test.txt");                     
                         out = new ObjectOutputStream(fileOut);
                         CollegeStudent student = new CollegeStudent("WMO","Asker");
                         out.writeObject(student);
                 } catch (Exception e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                 } finally {
                          try {
                                out.close();
                                fileOut.close();
                         } catch (IOException e) {
                         // TODO Auto-generated catch block
                                e.printStackTrace();
                         }
                 }

                 FileInputStream fileIn = null;
                 ObjectInputStream in = null;
                 try {
                        fileIn = new FileInputStream("test.txt");
                        in = new ObjectInputStream(fileIn);
                        CollegeStudent student = (CollegeStudent) in.readObject();
                        System.out.println(student);
                 } catch (Exception e) {
                        e.printStackTrace();
                 } finally {
                        try {
                             out.close(); fileOut.close();
                        } catch (IOException e) {
                             e.printStackTrace();
                        }
                 }
          }
}

class Student  implements Serializable{
        String name;
        public Student(String name) {
              super();
              this.name = name;
        }

        public Student() {
        }
        @Override
        public String toString() {
               return "["+ name + "]";
        }

        public String getName() {
              return name;
        }


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

class CollegeStudent extends Student  {
        String college="";

        public String getCollege() {
              return college;
        }

        public void setCollege(String college) {
              this.college = college;
        }

        public CollegeStudent(String college,String name) {
              super(name);
              this.college=college;
        }
        public CollegeStudent() {
              super("NO VAAL");
        }

        @Override
        public String toString() {
              return "[" + name + ","+college+"]";
        }
}

In the Above Example Lets Discuss the different Scenarios.

 Case 1: Student Class implements Serializable Interface. And College Student Does Not.

          CollegeStudent cs=new CollegeStudent(“College 1”,“Student 1”);
          //Save the Object.

          //Retrieve the Object and Print. The out put will be as Follows.

          [Student 1,College 1]

Case 2: Student Class Does Not. implements Serializable Interface. And CollegeStudent Does.

         CollegeStudent cs=new CollegeStudent(“College 1”,“Student 1”);
         //Save the Object.

         //Retrieve the Object and Print. The out put will be as Follows.

         java.io.InvalidClassException: serializing.CollegeStudent; no valid constructor
         at java.io.ObjectStreamClass.(ObjectStreamClass.java:455)
         at java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:297)
         at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1035)
         at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:302)
         at serializing.Serialize.main(Serialize.java:18)


Case 3: Both the Student and CollegeStudent implements Serializable Interface

If the parent Class Implements the Serializable then it is not required, if provided Not an Issue. It will behave as Case 1:

         CollegeStudent cs=new CollegeStudent(“College 1”,“Student 1”);
         //Save the Object.
         //Retrieve the Object and Print. The out put will be as Follows.
         [Student 1,College 1]


Case 4: Lets make some transient Fields. For example in Student class

         transient String name;

         CollegeStudent cs=new CollegeStudent(“College 1”,“Student 1”);
         //Save the Object.
         //Retrieve the Object and Print. The out put will be as Follows.
         [null,College 1]

Case 5: Lets make some transient Fields. For example in Student class

         transient String college="";
         CollegeStudent cs=new CollegeStudent(“College 1”,“Student 1”);
         //Save the Object.

         //Retrieve the Object and Print. The out put will be as Follows.
         [Student 1,null]

Tuesday, November 3, 2009

How is My Creativity

Hai Look at My Ashtray.




Flower Base


Here I prepared the Base By using Plaster of paris and Few Armatures.I got some Lucky bamboo to make it better.






Wednesday, September 2, 2009

AJAX: The Complete Tutorial Using Java Script

AJAX

Hai Guys, As I was sitting on bench in Organization I thought to write a Complete Article on AJAX , XMLHttpRequest Object and the web policies.


First of all let me introduce what is AJAX.

AJAX is the short for of Asynchronous JavaScript And XML In conventional web application the control of the sending request and handling response are in the hands of Browser. But in AJAX with use of JavaScript XMLHttpRequest Object it gives the complete handling of Sending Request and Handling the responses. Google was apparently the first to realize the power of XMLHttpRequest. With Gmail and Google Maps, they built applications that took advantage of this to provide a user.


AJAX comprises of different web development techniques as follows.

  1. XHTML, CSS for Data Presentations
  2. DOM(Document Object Model) for dynamic display of and interaction with data
  3. XML and XSLT for the interchange, and manipulation and display, of data, respectively
  4. XMLHttpRequest The Core JavaScript Object for asynchronous communication with Server
  5. JavaScript The Client Side Browser language to bring these technologies together

The above all technologies combinely help to create Interactive Rich Internet Applications.


What is XMLHttpRequest.

The XMLHttpRequest is the JavaScript object works as the key to AJAX. It has been available ever since Internet Explorer 5.5 was released in July 2000, as I mentioned above it was not fully discovered before people started to talk about AJAX and Web 2.0 in 2005.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

In the AJAX the data can be returned as text or XML, here in text you can return the Complete HTML file as response if required.Before AJAX people used to Apply this by using IFrame by setting the URL.


XMLHttpRequest Life Cycle:

  1. create an XMLHttpRequest object (or equivalent Active X control in IE)
  2. Set the URL in XMLHttpRequest in which we want to connect;
  3. Set the callback handler javascript method to process response data;
  4. call the send() method, passing in any data to be posted;
  5. Program the callback handler method in such a way that it will process the response in meaningful way.


XMLHttpRequest Life Cycle in Detail:


1. Create the XMLHttpRequest object

It is the first and most straightforward step in AJAX implementation.As simple as any Object creation in any language in Javascript also we will define as follows.

var reqObj = new XMLHttpRequest();

This Object will work with almost all the web browsers other than Internet Explorer (But in later IE releases they started supporting for this..)),

To make the Object Standardized for all the web browsers we can define a method as follows.



 function createXMLHttpRequest() {
    try { return new XMLHttpRequest(); } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) {
        alert("XMLHttpRequest not supported");
        return null;
    }
 }

[An Active X control is a type of embeddable Windows program component.]

function createRequestObj() {
       if (window.ActiveXObject) {
          xhr = new ActiveXObject("Microsoft.XMLHttp");
       } else {
          xhr = new XMLHttpRequest();
       }
    }


2. Setting Up the Request URL.

To make a call to the server, we first specify the URL that we want to connect to by the use of open() method in XMLHttpRequest, passing in the request URL.


xhReq.open("get", "studentDeatils.jsp", true);


XMLHttprequest Supports the following methods for making the Requests.


void open(DOMString method, DOMString url);

void open(DOMString method, DOMString url, boolean async);

void open(DOMString method, DOMString url, boolean async, DOMString? user);

void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);

void setRequestHeader(DOMString header, DOMString value);

void send();

void send (Document data);

void send ([AllowAny] DOMString? data);

void abort();


For Handling the response API supports the following methods.


readonly attribute unsigned short status;

readonly attribute DOMString statusText;

DOMString getResponseHeader(DOMString header);

DOMString getAllResponseHeaders();

readonly attribute DOMString responseText;

readonly attribute Document responseXML;


States of The XMLHttpRequest :

The readyState attribute, is the attribute provides current state of the XMLHttpRequest we made.


const unsigned short UNSENT = 0;

const unsigned short OPENED = 1;

const unsigned short HEADERS_RECEIVED = 2;

const unsigned short LOADING = 3;

const unsigned short DONE = 4;

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All HTTP headers have been received. Several response members of the object are now available.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)

The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

OPENED state has an associated send() flag that indicates whether the send() method has been invoked. It can be either true or false and has an initial value of false.

DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.


Note that we can POST data to the server (typically in XML format), or for simple cases, we could use GET and append some parameters to the URL. In the latter case, we'd just pass null to the send() method.

We used to pass in a local URL to the site from which the page is loaded. For security reasons:[The Cross URL XMLHttpRequest Will be discussed later. Viz Cross XHR], The Browsers Policies won't let you make an XMLHttpRequest to a URL from a different host to that from which the page was loaded.


3.Process data in the callback handler

As the Name says the call back method will not be executed at once, but rather asynchronously. Once the response came from the Server for every status of XMLHttpRequest.readyState this method will be invoked.

function responseProcessingFunction() {

// state of 4 means request completed

if (xhr.readyState == 4) {

var responseXML = xhr.responseXML;

// ... process the response ...

}

}


The resadyState = 4 means the request is DONE.


Limitation of Ajax

As the name suggests AJAX requires JavaScript Enabled Browsers.If the Browser doesn’t support or disabled the Application will not be running in web browsers. This alone means that AJAX applications will not work in web browsers and devices that do not support JavaScript. For this reason it is not accessible to many typical Web users
This is one of the limitations of the technology but as it’s having so many features the technology has many drawbacks too.

Future of Ajax:

AJAX is an extension of DHTML programming, adding the capability to dynamically send and retrieve data from the web server in response to user actions.The biggest challenges in creating Ajax applications are not technical. The core Ajax technologies are mature, stable, and well understood. Instead, the challenges are for the designers of these applications: to forget what we think we know about the limitations of the Web, and begin to imagine a wider, richer range of possibilities.
AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.Ajax has changed the face of the web forever. Save for some of the browser enhancements and a few other technologies, I dare to say that it’s had the most significant impact on the way we use the internet in its short life.


A Simple practical Example in JSP.


AjaxExample.html



<script language="JavaScript">
    function concatName()
    {
      // Create the XML request 
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      var URL="concat.jsp?firstName="+firstName+"&lastName="+lastName;
      xmlReq = null;
      if(window.XMLHttpRequest)
         xmlReq = new XMLHttpRequest();
      else if(window.ActiveXObject)               
      xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
      if(xmlReq==null){
         alert('Failed to Create Request.....')
         return; // Failed to create the request
      }

      // Anonymous function to handle changed request states
      xmlReq.onreadystatechange = function()
         {
             switch(xmlReq.readyState){
              case 0:              // Uninitialized
                      break;
              case 1: // Loading
                      break;
              case 2: // Loaded
                      break;
              case 3: // Interactive
                      break;
              case 4: // Done!
              // Alerting teh response as Text, and processing the responseXML(We are responding         as and XML from Server.)
                      processResponseText(xmlReq.responseText);
                      break;
              default:
                      break;
            }
         }
      // Make the request
      xmlReq.open ('GET', URL, true);
      xmlReq.send (null);
   }

   function processResponseText(responseText){
      var fullName=responseText;
      document.getElementById("concatName").value=fullName;
   }
</script>

AJAX Example

A Simple Concatenation Function Using AJAX First Name +<br/> Last Name -- <input type="button" value="Concatenate Name" onclick="concatName()"> -- ConcatenatedName= <input id="concatName"> </BODY> </HTML>
Concat.jsp
<%
    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");
    String fullName=firstName+" "+lastName;
    <%=fullName%>
    %>

AJAX Example This Page have simple the Concatenating Java Code.Just a replacement of Java Servlet to make the Example Simpler.

Reference:

http://www.javamex.com/tutorials/ajax/xmlhttprequest.shtml

http://www.w3.org/TR/2009/WD-XMLHttpRequest-20090820/

http://www.w3schools.com/Ajax/

And Obviously Google,