Ad

Saturday 6 September 2014

Collections algorithm - rotate,frequency,min,max and disjoint with sample program

In the post "Collections algorithm" we have seen about the algorithms reverse,shuffle,swap,fill and replace available in Collections class. Here we will see about the below remaining algorithm available in java.util.Collections.
  • rotate - This static method will rotate the specified list forward or backward by a specified distance.To move the list forward provide the distance as positive integer and to move backward provide the distance as negative integer.
  • frequency- This static method will return the count of the specified element exist in the specified list.
  • min- This static method will return the minimum element of the specified list according to the natural ordering of the element in the list.
  • max  - This static method will return the maximum element of the specified list according to the natural ordering of the element in the list.
  • disjoint - This static method will return true, if the two specified collection has no common elements between them.It will return false, if there is any common element between them.
Below sample program will illustrate how these methods can be used.

import java.util.ArrayList;                                                                                                                           
import java.util.Collections;
import java.util.List;

public class CollectionsSample {

public static void main(String[] args) {
CollectionsSample collectionsSample= new CollectionsSample();
collectionsSample.rotate();
collectionsSample.frequency();
collectionsSample.min();
collectionsSample.max();
collectionsSample.disjoint();
}

private void rotate() {
List<String> list=initializeList();
System.out.println("Values in the list before rotating:"+list);
Collections.rotate(list,1);
System.out.println("Values in the list after rotating forward by 1 position:"+list+"\n");
list=initializeList();
System.out.println("Values in the list before rotating:"+list);
Collections.rotate(list,-1);
System.out.println("Values in the list after roating backward by 1 position:"+list+"\n");
}
private void frequency() {
List<String> list=initializeList();
System.out.println("Values in the list :"+list);
int count =Collections.frequency(list, "HYUNDAI");
System.out.println("Number of Hyundai element in the list:"+count+"\n");
}
private void min() {
List<String> list=initializeList();
System.out.println("Values in the list:"+list);
String minElement=Collections.min(list);
System.out.println("Minimum element in the list is:"+minElement+"\n");
}

private void max() {
List<String> list=initializeList();
System.out.println("Values in the list:"+list);
String maxElement=Collections.max(list);
System.out.println("Maximum element in the list is:"+maxElement+"\n");
}
private void disjoint() {
List<String> list=initializeList();
List<String> secondList=new ArrayList<String>();
secondList.add("RENUALT");
secondList.add("AUDI");
System.out.println("Values in the first list :"+list);
System.out.println("Values in the second List :"+secondList);
boolean isDisjointList=Collections.disjoint(list, secondList);
if(isDisjointList)
{
 System.out.println("Above two list does not have any elements in common");
}
else
{
System.out.println("Above two list have some elements in common");  
}
}
private List<String> initializeList()
{
List<String> list= new ArrayList<String>();
list.add("HYUNDAI");
list.add("FORD");
list.add("HYUNDAI");
list.add("ZEN");
list.add("MARUTHI");
return list;
}
}

OUTPUT:

Values in the list before rotating:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Values in the list after rotating forward by 1 position:[MARUTHI, HYUNDAI, FORD, HYUNDAI, ZEN]

Values in the list before rotating:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Values in the list after roating backward by 1 position:[FORD, HYUNDAI, ZEN, MARUTHI, HYUNDAI]

Values in the list :[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Number of Hyundai element in the list:2

Values in the list:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Minimum element in the list is:FORD

Values in the list:[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Maximum element in the list is:ZEN

Values in the first list :[HYUNDAI, FORD, HYUNDAI, ZEN, MARUTHI]
Values in the second List :[RENUALT, AUDI]
Above two list does not have any elements in common

Friday 5 September 2014

Collections algorithm - reverse,shuffle,swap,fill and replace with sample program

There are many algorithm available in java.util.Collections class which provides many static util methods.
All these method take one of the argument as the list or the collection where the algorithm need to be applied. Some of them are:
  • reverse    - This static method will reverse the order of the specified list.
  • swap         - This static method will swap the elements at the specified positions of the  list.
  • shuffle      - This static method will reorders all the elements in the list randomly.
  • fill             - This static method will fill/replace all the elements in the list with a specified value.
  • replaceAll- This static method will replace all the occurrence of one specified value in the list with                           another value
Below sample program will illustrate how these methods can be used.

import java.util.ArrayList;                                                                                                                          
import java.util.Collections;
import java.util.List;

public class CollectionsSample {

public static void main(String[] args) {
CollectionsSample collectionsSample= new CollectionsSample();
collectionsSample.reverse();
collectionsSample.swap();
collectionsSample.shuffle();
collectionsSample.fill();
collectionsSample.replace();
}

private void reverse() {
List<String> list=initializeList();
System.out.println("Values in List before reverse:"+list);
Collections.reverse(list);
System.out.println("Values in List after reverse:"+list);
System.out.println();
}
private void swap() {
List<String> list=initializeList();
System.out.println("Values in List before swap:"+list);
Collections.swap(list,1,3);
System.out.println("Values in List after swap:"+list);
System.out.println();
}
private void shuffle() {
List<String> list=initializeList();
System.out.println("Values in List before shuffle:"+list);
Collections.shuffle(list);
System.out.println("Values in List after shuffle:"+list);
System.out.println();
}

private void fill() {
List<String> list=initializeList();
System.out.println("Values in List before fill:"+list);
Collections.fill(list,"NA");
System.out.println("Values in List after fill:"+list);
System.out.println();
}
private void replace() {
List<String> list=initializeList();
System.out.println("Values in List before replace:"+list);
Collections.replaceAll(list,"Tennis","TableTennis");
System.out.println("Values in List after replace:"+list);
System.out.println();
}
private List<String> initializeList()
{
List<String> list= new ArrayList<String>();
list.add("Cricket");
list.add("Footbal");
list.add("Tennis");
list.add("Baseball");
return list;
}
}

Output:

Values in List before reverse:[Cricket, Footbal, Tennis, Baseball]
Values in List after reverse:[Baseball, Tennis, Footbal, Cricket]

Values in List before swap:[Cricket, Footbal, Tennis, Baseball]
Values in List after swap:[Cricket, Baseball, Tennis, Footbal]

Values in List before shuffle:[Cricket, Footbal, Tennis, Baseball]
Values in List after shuffle:[Tennis, Footbal, Cricket, Baseball]

Values in List before fill:[Cricket, Footbal, Tennis, Baseball]
Values in List after fill:[NA, NA, NA, NA]

Values in List before replace:[Cricket, Footbal, Tennis, Baseball]
Values in List after replace:[Cricket, Footbal, TableTennis, Baseball]

Thursday 4 September 2014

To secure and protect the sensitive information in serializable object

By using serialization we can save the  object state to the stream and we can  construct the saved object back from the stream when needed.Sometime we need to secure some attributes in our object to not to  get serialized i.e not to save its value.Consider the below code example where we are writing the StudentVo object to the file and reading back from it.

StudentVO.Java

import java.io.Serializable;                                                                                                                    

public class StudentVO implements Serializable {

private String loginId;

private  String password;

private String fullName;

private int age;

public StudentVO(String loginId, String password, String fullName,
int age) {
super();
this.loginId = loginId;
this.password = password;
this.fullName = fullName;
this.age = age;
}

@Override
public String toString() {
return "StudentVO [loginId=" + loginId + ", password=" + password
+ ", fullName=" + fullName + ", age=" + age + "]";
}
}

SerializerSample.java

import java.io.FileInputStream;                                                                                                              
import java.io.FileOutputStream;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializerSample {

private final static String  FILE_NAME="D:/objfile";

public static void main(String[] args) {
      StudentVO studentVO = new StudentVO("V01", "pwd", "John Peter", 20);
      SerializerSample serializerSample= new SerializerSample();
      serializerSample.serialize(studentVO);
      studentVO=serializerSample.deSerialize();
      System.out.println("Object deserialized from file is:"+studentVO.toString());
}

private void serialize(StudentVO  studentVO)
{
try {
    FileOutputStream fileOutputStream= new FileOutputStream(FILE_NAME);
      ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(studentVO);
   fileOutputStream.close();
   objectOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}

private StudentVO deSerialize()
{
StudentVO studentVO=null;
try
{
FileInputStream fileInputStream= new FileInputStream(FILE_NAME);
ObjectInputStream objectInputStream= new ObjectInputStream(fileInputStream);
studentVO=(StudentVO) objectInputStream.readObject();
   fileInputStream.close();
   objectInputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
return studentVO;
}
}

As we can see in the Class SerializerSample,first we will  write the object state to the file(in method serialize()) and then construct the object back from the file(in method deSerialize()).
When we run the program,we will get the below output:

Object deserialized from file is:StudentVO [loginId=V01, password=pwd, fullName=John Peter, age=20]

Since the password is an sensitive attribute,we should not save its value when serilaized into the file.
There are three ways to secure a serializable object
  1. Declaring the sensitive field as transient
  2. Declaring the field serialPersistentFields
  3. Defining writeObject and readObject methods
1)Declaring the sensitive field as transient

values for the attributes which are declared as transient will not be saved when the object is serialized.So declare the field password as transient in StudentVO as shown below,so that its state will not be saved.

private transient String password;                                                                                                              

2)Declaring the field serialPersistentFields

we can define the serializable fields that need to be saved using the attribute serialPersistentFields in the serializable class.This field should be initialized with an array of ObjectStreamField as shown below.

import java.io.ObjectStreamField;                                                                                                            
import java.io.Serializable;

public class StudentVO implements Serializable {
private String loginId;
private  String password;
private String fullName;
private int age;

private static final ObjectStreamField[] serialPersistentFields
 = {new ObjectStreamField("loginId", String.class),
      new ObjectStreamField("fullName", String.class),
      new ObjectStreamField("age",Integer.TYPE)};

public StudentVO(String loginId, String password, String fullName,
int age) {
super();
this.loginId = loginId;
this.password = password;
this.fullName = fullName;
this.age = age;
}

@Override
public String toString() {
return "StudentVO [loginId=" + loginId + ", password=" + password
+ ", fullName=" + fullName + ", age=" + age + "]";
}
}


We have defined only the fields loginid,fullName and age in the serialPersistentFields so that only this fields will be saved to the file on serialization and not the password field.

3)Defining writeObject and readObject methods in the Serializable Class

We can define the methods writeObject and readObject in the serializable class to control what information to be saved and to be retrieved back from the stream.

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

public class StudentVO implements Serializable {
private String loginId;
private  String password;
private String fullName;
private int age;
 public StudentVO(String loginId, String password, String fullName,
int age) {
super();
this.loginId = loginId;
this.password = password;
this.fullName = fullName;
this.age = age;
}

 private void readObject(ObjectInputStream ois) throws IOException,                                          
 ClassNotFoundException {
loginId=(String) ois.readObject();
fullName=(String) ois.readObject();
age=ois.readInt();
}
 private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.writeObject(loginId);
    oos.writeObject(fullName);
    oos.writeInt(age);
 }

@Override
public String toString() {
return "StudentVO [loginId=" + loginId + ", password=" + password
+ ", fullName=" + fullName + ", age=" + age + "]";
}
}

When the StudentVo object is serialized using writeObject method of the objectOutputStream,it will delegate the call to the method writeObject in serializable class StudentVO class.Thus only the fields loginId,fullName and age will be saved and not the password field.

OUTPUT:

When we run the SerializerSample class by using any of the above 3 versions of the StudentVO,we will get the below output

Object deserialized from file is:StudentVO [loginId=V01, password=null, fullName=John Peter, age=20]

As we can see in the output, the password field value was not saved during serialization.

Wednesday 27 August 2014

What is marker interface and can we write our own marker interface in java?

       We all know that marker interface is an empty interface which doesn't have any methods or fields defined in it.Serializable and cloneable are example for the marker interface.
  
         We have studied in various tutorials saying that the marker interface are used to indicate some signal to the Java compiler. Is this the correct definition for marker Intarface?The answer is 'NO'. The correct definition is:

    "By Implementing a marker interface we are allowing our class to be carried out a certain operation by an Util class".

For instance if we implement the Serializable Interface,we are allowing our class to be get serialized. In this case the Util class will be ObjectOutputStream which will write our object to the stream. So the  method writeObject of ObjectOutputStream  will check if the object passed to it has implemented the Serializable interface(By using instanceof).If it does it will continue to serialize the object, otherwise it will throw the NotSerializableException.

The next question comes to our mind, Can we write our own Marker interface? The answer is "YES".

 Lets start to write our own marker interface "Objectprinter".By implementing this marker interface,we are saying that our object values are allowed to be printed to a file by an Util class.In our case the util class which will write the object attribute values to a file is "ObjectPrinterUtil".Lets also define two classes
  •   Person which will implement this marker Interface "ObjectPrinter" and
  •   Department which will not implement it.

ObjectWriter.java

public interface ObjectPrinter {                                                                                                              

}

Person.java

public class Person implements ObjectPrinter{                                                                                    
  
 String name;
  
 int age;
  
 public Person(String name,int age)
 {
  this.name=name;
  this.age=age;
 }
  
 @Override
 public String toString() {
  return "Person [name=" + name + ", age=" + age + "]";
 }
}

Department.java

public class Department {                                                                                                                      
  
 private String departmentId;
 private String departmentName;

 public Department(String departmentId, String departmentName) {
  this.departmentId = departmentId;
  this.departmentName = departmentName;
 }

 @Override
 public String toString() {
  return "Department [departmentId=" + departmentId + ", departmentName="
    + departmentName + "]";
 }
}
 

ObjectPrinterUtil.java

public class ObjectPrinterUtil {                                                                                                             

 public static void main(String[] args) throws Exception {
  ObjectPrinterUtil objectPrinterUtil=new ObjectPrinterUtil();
  Person person= new Person("Ram", 20);
  Department department=new Department("D01","CSE");
  objectPrinterUtil.printObject(person);
  objectPrinterUtil.printObject(department);
 }
 

 public void printObject(Object object) throws Exception
 {
  if(object instanceof ObjectPrinter)
  {
   System.out.println("Value Printed to the File:"+object.toString());
  }
  else
  {
   throw new NonPrintableException();
  }
 }
}

class NonPrintableException extends Exception
{
 public NonPrintableException()
 {
  super("Object is not printable");
 }
}
  
  • printObject method of the ObjectPrinterUtil  is responsible for printing passed object attribute values to the console.
  • It will check if the passed object has implemented the ObjectPrinter Interface.If it does then it write the attribute value to the console else it will throw the Exception  NonPrintableException.

OUTPUT

Value Printed to the File:Person [name=Ram, age=20]
Exception in thread "main" test.NonPrintableException: Object is not printable
 at test.ObjectPrinterUtil.printObject(ObjectPrinterUtil.java:21)
 at test.ObjectPrinterUtil.main(ObjectPrinterUtil.java:10)

As we can see in the output,
  • Since the Person class implemented the ObjectPrinter marker Interface,its attribute values were printed to the console by the ObjectPrinterUtil.
  • Department doesn't implemented this interface,hence the values were not printed and NonPrintable Exception were thrown by the ObjectPrinterUtil. 

Monday 25 August 2014

To disable the contextmenu on rightclick of the link/anchor using jquery

    We sometimes need to disable the right click on the link due to security reasons, so that we don't show up the default context menu on our webpage. Using jQuery this can be easily implemented. Below is the sample page where we have two links(anchor) and we would need to disable the right click on the first link(Link1)

<html>
<head>                                                                                                                                                     
<title>To Disable right click</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

$(document).ready(function() {

$('#link1').bind("contextmenu",function(e){
alert("Right click not allowed");
return false;
});


});
</script>
</head>
<body bgcolor=white>
<a href="#" id="link1">Link1</a>
<BR>
<a href="#" id="link2">Link2</a>
</body>
.

As we can see in the JavaScript, we registered the handler to the element of id "link1" for the eventType "contextmenu".So this handler will be called when we right click on the link "Link1" and since we return as false the context menu will not be displayed.

Demo
Link1
Link2

If our requirement is to disable the right click on the whole webpage, then we need to register the handler on the document object as shown below:

$(document).bind("contextmenu",function(e){                                                                                      
alert("Right click not allowed");
return false;
});
 

Sunday 13 July 2014

java.lang.IllegalThreadStateException at java.lang.Thread.start

IllegalThreadStateException is thrown when you try to start the thread more than once on the same thread object instance.Start method can be invoked only when the Current thread state is "New".For other states like Runnable,Running  or waiting etc invoking start method will throw the IllegalThreadStateException.

Below sample will show the typical scenario where the IllegalThreadStateException will be thrown:

public class IllegalThreadStateSample {                                                                                                    

public static void main(String[] args) {
        ProcessThread processThread= new ProcessThread();
        Thread thread= new Thread(processThread,"ProcessThread");
        thread.start();//ProcessThread State will become "Runnable" and then "Running"
        thread.start();//Starting the ProcessThread for the second time
}

}

class ProcessThread implements  Runnable {

public void run() {
System.out.println("Thread started::"+Thread.currentThread().getName());
}
}

When we run this program,IllegalThreadStateException  will be thrown as shown below:

Thread started::ProcessThread                                                                                                                  
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at test.IllegalThreadStateSample.main(IllegalThreadStateSample.java:9)

  • When we create the thread object(i.e new Thread(processThread,"ProcessThread")),the State of the ProcessThread will be become "New".
  • Invoking the start method will make the state of the Processthread to "Runnable" or "Running" and the ProcessThread started its execution.
  • Since Start method is invoked on the same thread object for the second time whose state is not "New",IllegalThreadStateException is thrown

Friday 11 July 2014

Joining Threads using join method in java

By using join method in Thread, we can make one thread to wait until the other thread completes its execution.There are two overloaded methods of join:

t.join()
    - The current executing thread which invokes the above join method,will make it to wait until thread "t" completes its execution.In other words the current thread will resumes its execution only after thread "t" completes.

t.join(10000)
    - The current executing thread which invokes the above join method,will make it to wait  until thread "t" completes its execution.But one exception to this  is, the current thread can wait only up to a maximum of 10 seconds i.e if thread "t" doesn't complete in 10 seconds,current thread will resumes its execution even though thread "t" has not completed.

The below sample program will explain this behavior


public class ThreadJoinSample {                                                                                                                

public static void main(String[] args) {
System.out.println("Thread started::"+Thread.currentThread().getName());
ChildThread childThread= new ChildThread();
Thread thread=new Thread(childThread, "ChildThread");
thread.start();
try {
thread.join();
//thread.join(10000);
          System.out.println("Thread Resumed::"+Thread.currentThread().getName());
}
   catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread completed::"+Thread.currentThread().getName());
}

}

class ChildThread implements  Runnable {
public void run() {
System.out.println("Thread started::"+Thread.currentThread().getName());
try {
Thread.sleep(20000);//Sleep for 20 seconds
}
    catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread completed::"+Thread.currentThread().getName());
}

}

The Main thread(ie main() method) creates and starts a new ChildThread and invokes  the join method on the Childthread.As a result the main thread will wait until the childThread completes its execution.When we run the above program,we will get the output as shown below:

Thread started::main
Thread started::ChildThread                                                                                                                      
Thread completed::ChildThread
Thread Resumed::main
Thread completed::main

As we can see in the output,the Main thread has resumes its execution only after the Child Thread has completed.

Now use the other overloaded join method in the above program i.e replace join() with join(10000).
Now the output will be:

Thread started::main
Thread started::ChildThread                                                                                                                      
Thread Resumed::main
Thread completed::main
Thread completed::ChildThread

Since the Main Thread can wait only maximum of 10 seconds and the ChildThread will take 20 seconds to completes its execution,the main thread has resumed its execution even though the ChildThread has not completed.

Wednesday 18 June 2014

Parsing XML using stax parser in Java

STAX API uses the pull parsing methodology,where we call the methods on the Stax Library and depending on the events returned we get the values from the XML.When parsing using STAX,it will return the different events depending on the XML element type which it is current referring to.

Lets say we want to parse the below XML and we need to set the values in the Employee object.

employee.xml

<?xml version="1.0" encoding="UTF-8"?>                                                                                        
<employeedetails>
  <employee id="1">
<name>Rahul</name>
<age>25</age>
               <department>IT</department>
    </employee>
    <employee id="2">
<name>John</name>
<age>26</age>
               <department>IT</department>
    </employee>
    <employee id="3">
<name>Peter</name>
<age>29</age>
                <department>HR</department>
    </employee>
</employeedetails>

Employee.java

public class Employee {

private String empId=null;                                                                                                          
private String empName=null;
private String age=null;
private String department=null;

/**
* @return the empId
*/
public String getEmpId() {
return empId;
}

/**
* @param empId the empId to set
*/
public void setEmpId(String empId) {
this.empId = empId;
}

/**
* @return the empName
*/
public String getEmpName() {
return empName;
}

/**
* @param empName the empName to set
*/
public void setEmpName(String empName) {
this.empName = empName;
}

/**
* @return the age
*/
public String getAge() {
return age;
}

/**
* @param age the age to set
*/
public void setAge(String age) {
this.age = age;
}

/**
* @return the department
*/
public String getDepartment() {
return department;
}

/**
* @param department the department to set
*/
public void setDepartment(String department) {
this.department = department;
}

@Override
public String toString() {
return "Employee [empId=" + empId + ", empName=" + empName + ", age="
+ age + ", department=" + department + "]";
}
}



Below is the sample code for parsing the employee.xml and to set the value in list of employee object.

import java.io.InputStream;  
import java.util.ArrayList;
import java.util.List;
                                                                                                                                                             
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
                                                                                                                                                               
public class StaxExample {

public static void main(String[] args) {
      List<Employee> employeeList=null;
      Employee employee=null;
      try
      {
      XMLInputFactory inputFactory= XMLInputFactory.newFactory();
      InputStream inputStream=StaxExample.class.getClassLoader().
                                                 getResourceAsStream("employee.xml");
      XMLStreamReader xmlStreamReader=inputFactory.createXMLStreamReader(inputStream);
      String elementName="";
      while(xmlStreamReader.hasNext())
      {
     int event=xmlStreamReader.next();
     if(event==XMLStreamConstants.START_ELEMENT)
     {
     elementName=xmlStreamReader.getLocalName();
     if("employeedetails".equalsIgnoreCase(elementName))
     {
     employeeList=new ArrayList<Employee>();
     }
     else if("employee".equalsIgnoreCase(elementName))
     {  
     employee=new Employee();
     if(xmlStreamReader.getAttributeCount()>0 && 
     ("id").equalsIgnoreCase(xmlStreamReader.getAttributeLocalName(0)))
     employee.setEmpId(xmlStreamReader.getAttributeValue(0));
     }
     }
     else if(event==XMLStreamConstants.CHARACTERS)
     {
     String value=xmlStreamReader.getText();
     if(elementName.equalsIgnoreCase("name"))
     {
     employee.setEmpName(value);
     }
     else if(elementName.equalsIgnoreCase("age"))
     {
     employee.setAge(value);
     }
     else if(elementName.equalsIgnoreCase("department"))
     {
     employee.setDepartment(value);
     }
     }
     else if(event==XMLStreamConstants.END_ELEMENT)
     {
     elementName=xmlStreamReader.getLocalName();
     if("employee".equalsIgnoreCase(elementName))
     {
     employeeList.add(employee);
     }
     elementName="";//Reset the elementName(TagName)
     }
      }
      System.out.println("Values Parsed from XML is:"+employeeList.toString());
      }
      catch(Exception e)
      {
     e.printStackTrace();
      }
  }
}

  • The starting point of using STAX API is to get the XMLInputFactory Object.
  • Then we get the XMLStreamReader from this factory by passing the inputstream for the xml to be parsed.Make sure the employee.xml is in the classpath.
  • XMLStreamReader behaves as the pointer to the xml and when we invoke the next() method ,it will return the event of the Current xml element type and moves to next element in the xml.
  • When the start element of any xml tag is reached,it will return the event XMLStreamConstants.START_ELEMENT.Then by using the getLocalName() method we can get the name of the xml tag.To get the value of the attribute in the current element, we can use the method getAttributeValue(index),where index is the position of the attribute in in the corresponding tag
  • When the end element of any xml tag is reached,it will return the event XMLStreamConstants.END_ELEMENT
  • when the value of any tag is reached,it will return the event XMLStreamConstants.CHARACTERS and we can use the method getText() to get the value enclosed within the tag
OUTPUT


Values Parsed from XML is:[Employee [empId=1, empName=Rahul, age=25, department=IT],   Employee [empId=2, empName=John, age=26, department=IT], Employee [empId=3, empName=Peter, age=29, department=HR]]                                                                                     

Friday 13 June 2014

How to implement SelectAll Checkbox using Jquery

Some times we may need to implement the Selectall checkbox in our pages.On Checking the Select all check box,it will check all the check boxes under it and unchecking it,will deselect all the Check boxes.Jquery sample for Select All functionality is shown below

<html>
  <head>
    <title>Selecall Checkbox sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">
    $(document).ready(function() {
     
     /*Handler For SelectAll Checkbox*/ 
      $("#selectallchkbox").change(function(){
        $('.tvChkBox').prop("checked",$(this).prop("checked"));
       });

      /*Handler For rest of the checkbox*/      
       $('.tvChkBox').change(function(){
       if( $('.tvChkBox').length==$('.tvChkBox:checked').length)
         {
           $("#selectallchkbox").prop("checked",true);    
         }
         else
         {
           $("#selectallchkbox").prop("checked",false);
         }         
       });

    });
</script>
</head>
<body>
<table bgcolor="#E9E9E9" border="1">
<tr>
<td>
<B>Selectall Sample</B><BR><BR>
<table border='1'>
<tr>
<th><input type="checkbox" id="selectallchkbox"/></th>
<th>TV Brand</th>
<th>Rank</th>
</tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox1"/></td><td>Sony</td><td>1</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox2"/></td><td>Samsung</td><td>3</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox3"/></td><td>LG</td><td>2</td></tr>
<tr><td><input class="tvChkBox" type="checkbox" id="tvChkBox4"/></td><td>Onida</td><td>4</td></tr>
</table>
</td>
</tr>
</table>
</body>
</html>

  • When the page document is ready(i.e on load of the page),the Javascript code inside the $(document).ready will be get executed.
  • We registered two handlers in the ready section.
  • Change Handler for SelectAll CheckBox- On change of SelectAll check box,if it is checked we select all the Checkboxes with the class "tvChkBox" and  if it is unchecked we uncheck the same(by setting the property "checked" to true or false).
  • Change Handler for rest of the Checkboxes - On change of the Checkboxes with the class "tvChkBox",if all the Checkboxes with  the class "tvChkBox" is checked we will check the selectall Checkbox,otherwise will uncheck the selec all checkbox(by setting the property "checked" to true or false).  
 Demo:


Selectall Sample

TV Brand Rank
Sony1
Samsung3
LG2
Onida4

Thursday 12 June 2014

How to load dropdown list dynamically using Jquery

In most scenarios we may need to load the drop down list dynamically with the values fetched from the database.Using jquery loading the dropdown list is very simple and easy to code.Lets assume we need to load the drop down with the city names fetched from the backend.The sample code for this is shown below:

<html>                                                                                                                                                    
<head>
<title>Dropdown sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

function Load() {
   var cityobjArray = [
  {cityId:1,cityName:"Chennai"},
  {cityId:2,cityName:"Mumbai"},
  {cityId:3,cityName:"Banglare"},
  {cityId:4,cityName:"Pune"},
   ];
var cityDropdown = $('#cityDrpDown');

$.each(cityobjArray , function(index, cityobj) {
        cityDropdown.append(
         $('<option/>', {
                          value: cityobj.cityId,
                          text: cityobj.cityName
                        })
           );
        });
}

function unLoad() {
 $('#cityDrpDown').empty();
}
</script>
</head>
<body>
<table border="1">
<tr>
<td>
<B>To Load DropdownList dynamically</B><BR><BR>
Select City:<select  id="cityDrpDown"/></select>
<BR><BR>
<input type="button" value="Load" onclick="Load()"/>
<input type="button" value="Unload" onclick="unLoad()"/>
</td>
</tr>
</table>
</body>
</html>

  • Lets assume cityobjectArray is the Json data array we fetched from database which we need to load in the drop down list.
  • As shown in Load method,we iterate the cityobjectArray using $.each jquery method and for each cityobject we add the option object ("referenced using $(<option/>") to the dropdown list.The value and text of the Option object will set from Cityobject attributes cityid and cityname. 
  • To clear the dropdown list we use the jquery method empty() as shown in unLoad() method.

Demo:


To Load DropdownList dynamically

Select City:



Wednesday 11 June 2014

To check/uncheck the Checkboxes using Jquery


We may need to precheck a check box, when the page loads or we may need to check it depending on any event.Using Jquery it is very simple and easy to implement.Below is the sample code to check or uncheck a single check box or all checkboxes.

<html>                                                                                                                                                    
<head>
<title>CheckBox sample</title>
<script type="text/javascript" src="jquery-2.1.1.min.js" ></script>
<script type="text/javascript">

function check() {
   $("#checkbox1").prop("checked", true);
}

function uncheck() {
   $("#checkbox1").prop("checked", false);
}

function checkall() {
   $("#checkGrp input[type=checkbox]").each(function()
    {
      $(this).prop("checked",true);
    } );
}

function uncheckall() {
   $("#checkGrp input[type=checkbox]").each(function()
   {
    $(this).prop("checked",false);
   });
}
</script>
</head>
<body bgcolor=white>

<input type="checkbox" id="checkbox1"/>BreakFast
<BR>
<input type="button" value="check" onclick="check()"/>
<input type="button" value="uncheck" onclick="uncheck()"/>
<BR><BR>
<div id="checkGrp">
<input type="checkbox" id="checkbox2"/>Coffee
<BR>
<input type="checkbox" id="checkbox3"/>Tea
<BR>
<input type="checkbox" id="checkbox4"/>Bread
<BR>
<input type="checkbox" id="checkbox5"/>Burger
<BR>
<input type="button" value="CheckAll" onclick="checkall()"/>
<input type="button" value="UncheckAll" onclick="uncheckall()"/>
</div>
</body>
</html>

  • To check the Checkbox,we set the Property of the checkbox with id "checkbox1" to true as shown in function check()
  • To uncheck the Checkbox,we set the Property of the checkbox with id "checkbox2" to false as shown in function uncheck()
  • To checkall the checkboxes,we iterate all the checkboxes object under the div "checkGrp" and set the property of each checkbox to true as shown in function checkall().
  • To uncheck all the checkboxes,we iterate all the checkboxes object under the div "checkGrp" and set the property of each checkbox to false as shown in function uncheckall().

Demo

BreakFast


Coffee
Tea
Bread
Burger