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.