Saturday, 7 February 2015

What is Type Erasure in Java Generics

Introduction:
Generics is one the most important features introduced in JDK 1.5.this feature is provided to perform compile-time checking and removing risk of ClassCastException that occures at runtime generally working with collections.

The whole collection framework re-written to use generics for type-safety. Lets discuss, how we can avoid type-safety in JDK 1.5 through examples.

JDK 1.4 coding style:
List collection = new ArrayList();
colection.add("This is a String object");
collection.add(new Integer(10));
collection.add(new UserdefinedObject());

for(int index = 0; index < collection.size(); index++) {
     Integer int = (Integer) collection.get(index);
}
Here, there is no type-check validation performed at compilation time. Hence, any kind of objected can be able to added the list. But while iterating at run-time there is no guarantee that all the elements are of type Integer. So there are more chances of getting ClasscastException.

To overcome this limitation, generics are introduced in JDK 5.

JDK 1.5 coding style:
List<Integer> collection = new ArrayList<Integer>();
collection.add(new Integer(10));
collection.add(new UserdefinedObject()); // Gives compilation error

for(Integer int : collection) {
    // No explicit casting required, since the collcetion object have only Integer objects.
}

What is Type Erasure in Generics:
To discuss this, lets take an example. We have a requirement to create two similar methods(overloading), one to accept list of Employee objects and another to accept list of Assests objects to perform required business logic.

So, our code looks like as follows:
public Double calculateCost(List<Employee> empList) {
     // business logic 
}
public Double calculateCost(List<Asset> assetList) (
     // business logic 
}
The above gives compilation error, saying "Method has the same easure as another method in type".

The reason for above compilation error is due to Java generics uses type erasure. It means that, Java generics is implemented on the compilation level. The byte code generated from compiler does not contain type information of generic type for the run-time execution.

After compilation, both list of employee and list of assest become List.
If we observe the code by using Java Decompiler, the code looks like below:
public Double calculateCost(List empList) { }
public Double calculateCost(List assetList) { }
Hence, while runtime both methods appears same signature. So JVM gets ambiguity to call which method to perform required operation.

In the case of above situations, we can use Wildcard characters in the methods signature as follows:
public Double calculateCost(List<?> list) { }

Note:
During the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded or Object if the type parameter is unbounded.

Reference : http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
.

Wednesday, 8 October 2014

Examples of Comparable, Comparator, equals() & hashCode()

We can discuss the use of Comparable, Comparator interfaces & equals(), hashCode() methods by using some problem description.

In Java, there is an utility called Collections to perform most of the required operations on collection framework classes.
One of the most frequently used operation is Sorting. We can do the sorting by using Collections.sort() method.
Collections.sort() method has the following two forms.

sort(List list) - Sorts the specified list into ascending order, according to the natural ordering of its elements.
sort(List list, Comparator c) - Sorts the specified list according to the order induced by the specified comparator.

Comparable and Comparator are two interfaces provided by Java Core API. From their names, we can tell they may be used for comparing stuff in some way. But what exactly are they and what is the difference between them?

Comparable:Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo().
Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

Comparator:
Class whose objects to be sorted do not need to implement this interface. Some third class can implement this interface to sort.
Using Comparator interface, we can write different sorting based on different attributes of objects to be sorted.You can use anonymous comparator to compare at particular line of code.


Parameter
Comparable
Comparator
Sorting logic
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.
Implementation
Class whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by id
Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id

Sorting method
int compareTo(Object o1)
This method compares this object with o1 object and returns a integer.Its value has following meaning
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1
int compare(Object o1,Object o2)
This method compares o1 and o2 objects. and returns a integer.Its value has following meaning.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
Calling method
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Package
Java.lang.Comparable

Java.util.Comparator

equals() & hashCode() methods: In Java every object has access to equals() & hashCode() methods, since these are available in java.lang.Object class & Object class is super class by default for all the classes. The main intention of these methods are to compare the given two or more objects and identify their equality.

The default implementation of equals() method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison".


These two methods have significant relationship with each other. If we want to override any one of the methods, need to override both the methods. We will discuss why do we need to override both, otherwise what is the impact.


The equals() method must exhibit the following properties:
  1. Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)
  2. Reflexivity: For all non-null references, a.equals(a)
  3. Transitivity: If a.equals(b) and b.equals(c), then a.equals(c)
  4. Consistency with hashCode(): Two equal objects must have the same hashCode() value

Why do we need to override equals() method: An object might have many number of variables, but we may need to consider only few variables into consideration while comparing the objects.
Suppose, customer landed on some eCommerce application and would like buy some article. Article may have many number of properties such as name, capacity, cost, availability, seller_name, seller_location, delivery_date..etc. But while coming to comparison, customer may consider name, price & delivery_date.
Hence, it require to apply equals() methods to lookup only these properties while determining equality. 

Why to override hashCode() method: hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable, HashMap like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
The hashCode() method of objects is used when we insert them into a HashTable, HashMap or HashSet. More about hastables on Wikipedia.org for reference.
To insert any entry in map data structure, we need both key and value. If both key and values are user define data types, the hashCode() of the key will be determine where to store the object internally. When require to lookup the object from the map also, the hash code of the key will be determine where to search for the object.
The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The HashTable then iterates this area (all keys with the same hash code) and uses the key's equals() method to find the right key. Once the right key is found, the object stored for that key is returned.
So, as we can see, a combination of the hashCode() and equals() methods are used when storing and when looking up objects in a HashTable.

NOTES:
1.       Always use same attributes of an object to generate hashCode() and equals() both. As in our case, we have used employee id.
2.       equals() must be consistent (if the objects are not modified, then it must keep returning the same value).
3.       Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
4.       If you override one, then you should override the other.

Problem Statement:
There are 2 travel companies who have buses travelling from dest A to dest B. they want to merge their buses timetable and produce it to the customer so that they can find out which bus is effective for them and choose bus accordingly(o/p).

They will provide a text file having the I/P as shown above and we need to give O/P as shown above.

Conditions:
1) If the bus travel time is greater than 1hr then it should not be displayed.
2) If the both the travel agency having same time of dept and arrival then we need to show only volvo travel time and ignore BMW.
3) we need to format O/P as
a) if busA starts at 10 and arrives at 11, if busB starts at 10:05 and arrives at 11, then busB has to come before busA.
b) if busA starts late and arrives before busB,then busA has to come before busB.
c) if busA starts at same time as busB but reaches before,then busA has to come before busB.

Input file:


volvo 10:10 11:05
volvo 10:15 11:05
volvo 11:00 12:15
volvo 11:50 12:50
volvo 12:00 12:45
BMW 10:05 11:05 
BMW 10:10 11:05
BMW 10:50 11:45
volvo 10:50 11:45
BMW 11:05 12:15

Output:
volvo 10:15 11:05
volvo 10:10 11:05
BMW 10:05 11:05
volvo 10:50 11:45
volvo 12:00 12:45
volvo 11:50 12:50

BusInfoVO: Its a Data transfer object which holds the information of a bus.
package com.exer.files.vo;

import java.io.Serializable;
import java.util.Date;

public class BusInfoVO implements Comparable<BusInfoVO>, Serializable {
 
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 
 private String busType;

 private Date startTime;

 private Date endTime;

 private transient Long duration;
 
 public String getBusType() {
  return busType;
 }

 public void setBusType(String busType) {
  this.busType = busType;
 }

 public Date getStartTime() {
  return startTime;
 }

 public void setStartTime(Date startTime) {
  this.startTime = startTime;
 }

 public Date getEndTime() {
  return endTime;
 }

 public void setEndTime(Date endTime) {
  this.endTime = endTime;
 }

 public Long getDuration() {
  return duration;
 }

 public void setDuration(Long duration) {
  this.duration = duration;
 }

 @Override
 public int compareTo(BusInfoVO busInfo) {
  
  if((this.getStartTime().equals(busInfo.getStartTime())) && (this.getEndTime().equals(busInfo.getEndTime()))) {
   return 0;
  } if((this.getStartTime().equals(busInfo.getStartTime())) || (this.getEndTime().equals(busInfo.getEndTime()))) {
   return this.getDuration() < busInfo.getDuration() ? -1 : 1;
  } else if((this.getStartTime().after(busInfo.getStartTime())) && (this.getEndTime().before(busInfo.getEndTime()))) {
   return -1;
  } else if(this.getStartTime().before(busInfo.getStartTime())) {
   return -1;
  }
  return 1;
 }
 
 @Override
 public boolean equals(Object busInfo) {
  boolean result = false;
  
  if (busInfo == null || (this.getClass() != busInfo.getClass())) {
   return result;
  }
  
  BusInfoVO other = (BusInfoVO) busInfo;
  if((this.getStartTime().equals(other.getStartTime())) && (this.getEndTime().equals(other.getEndTime()))) {
   return true;
  }
  
  return result;
 }
 
 @Override
 public int hashCode() {
  int hash = 10;
  hash = hash + this.getStartTime().getHours() + this.getStartTime().getMinutes();
  hash = hash + this.getEndTime().getHours() + this.getEndTime().getMinutes();
  return hash;
 }

}


Here BusInfoVO class implementing Comparable interface and overrides compareTo() method.

FilesReader.java: Where data can be read and processed as expected output.
package com.exe.files.reader;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.TreeSet;

import com.exer.files.vo.BusInfoVO;

public class FilesReader {

 private static DateFormat dateFormat = new SimpleDateFormat("HH:mm");
 
 private List<BusInfoVO> busInfoVOList;

 public List<BusInfoVO> getBusInfoVOList(String path) {
  if(path != null) {
   File folder = new File(path);
   File[] listOfFiles = folder.listFiles(); 
   busInfoVOList = new ArrayList<BusInfoVO>();
   for (int i = 0; i < listOfFiles.length; i++) {
    try (Scanner scanner = new Scanner(listOfFiles[i])) {
     while (scanner.hasNextLine()) {
      String[] info = scanner.nextLine().toString().split(" ");
      if (info != null && info.length > 0) {
       BusInfoVO vo = new BusInfoVO();
       vo.setBusType(info[0]);
       Date startTime = dateFormat.parse(info[1]);
       Date endTime = dateFormat.parse(info[2]);
       vo.setStartTime(startTime);
       vo.setEndTime(endTime);
       vo.setDuration((endTime.getTime() - startTime.getTime()) / (60 * 1000)); // In minutes.
       if(vo.getDuration() <= 60) {
        busInfoVOList.add(vo);
       }
      }
     }
    } catch(ParseException | FileNotFoundException exp) {
     exp.printStackTrace();
    }
   }
   Collections.sort(busInfoVOList, new Comparator<BusInfoVO>() {

    @Override
    public int compare(BusInfoVO o1, BusInfoVO o2) {
     return o2.getBusType().compareTo(o1.getBusType());
    }
   });
   return busInfoVOList;
  }
  
  return null;
 }
 
 public static void main(String[] args) throws ParseException, FileNotFoundException {
  String path = "D:\\PARAMESH\\FILES";
  FilesReader reader = new FilesReader();
  List<BusInfoVO> list = reader.getBusInfoVOList(path);
  TreeSet<BusInfoVO> set = new TreeSet<BusInfoVO>();
  for(BusInfoVO vo : list) {
   set.add(vo);
  }

  for(BusInfoVO vo : set) {
   System.out.println(vo.getBusType() + " " + dateFormat.format(vo.getStartTime()) + " " + dateFormat.format(vo.getEndTime()));
  }
 }
}

Here, we used(@ L 50) "sort(List<T> list, Comparator c)" method to sort the list based on the name field of BusInfoVO.

While adding to the set.add(vo) (@L 69), its looks for the equals() method definition available in BusInfoVO class and compares the given object with all existing objects in the set.
If equals returns : true - Will add the given object to the set.
                             false - Will not add the given object to the set.
Also, when we add the elements in TreeSet, it internally calls compareTo() method available in the given for sorting.

Tuesday, 26 August 2014

Backbone.js


What is Backbone.js?

Backbone.js is a JavaScript library with a RESTful JSON interface and is based on the model–view–presenter (MVP) application design paradigm.
Its very lightweight as its only dependency is on one JavaScript library(Underscore.js).
Backbone was created by Jeremy Ashkenas.
(OR)
Backbone.js is a JavaScript client-side (front end) framework, which helps to organize your code and makes it easier to develop single page applications. It allows you to structure JavaScript code in an MVC (Model, View , Controller) fashion

Model: It is a part of your code that populates and retrieves the data
View: It is the HTML representation of this model
Controller: It enables you to save your javascript application via a hashbang URl

The main component of Backbone.js are:

Model
View
Collection
Router
Event class object

Models and Collections
Models in Backbone represent data, let’s say I have blog, which contains posts, comments, categories, tags, etc. In this case blog post is a model, category is collection, comment is a model.

Views
Views contain instructions how to render models or collections, once we receive some data from the server – view picks it up, formats it, handles adding new or removing models, etc and passes this information to template (Handlebars, Underscore or any other template engine).

Routers
Routers are responsible for navigation. Backbone.js uses HTML5 history API and gracefully degrades in old browsers (you guessed it – Internet Explorer). When building with backbone.js – in most cases you are building one page page application, so there are no page refresh, that’s router’s job. It directs application and where user wants to go. For example if I’m on home page of my blog and need to view single blog post, I click on read more button, router passes this post ID to view, view requests model attached to this view to fetch content from the server and then renders the content to template.

Advantages:
By using JavaScript with the minimal set of data-structuring ( models & collections) and user interface (views & URLs) it enables you to develop a web application
Backbone is best useful to develop MVC like web applications, single page web applications or complex JavaScript web applications in an organized and structured manner without JavaScript code mixing with HTML
Provides key value binding and custom events
API with tons of functions
Robust event handling
API connetion over a RESTful JSON interface.


When to use Backbone.js?

When we need to use JavaScript heavily in order to make responsive and interactive web applications.
A common problem with large JS web application developed is that they can become pretty messy really quickly. The lack of structure makes the code hard to maintain. This is where Backbone comes into play. It provides structure to organize the code and increase maintainability. Backbone is not the only framework like this; in fact, there are many JS frameworks that attempt to offer similar benefits, like Ember.js, Angular.js and so on. Backbone is one of the most widely used frameworks in its category.

Backbone.js has hard dependency on underscore.js and a soft dependency on jQuery. It’s made up of the following modules:
  • Views
  • Events
  • Models
  • Collections
  • Routers

Video tutorial on Backbone.js.

. Best IDE's for Backbone.js are Sublime Text, Atom

Thursday, 13 March 2014

Best approach for formatting date in java


The most common approach to format the date as required by using SimpleDateFormat.


This approach causes problems when multiple threads access the same instance of the class variable, due to lack of synchronization.


The below are the most frequent exceptions will occurs:
  • java.lang.NumberFormatException
  • java.lang.ArrayIndexOutOfBoundsException

There are two approaches to handle these exceptions in Multi-threading environment.
  1. By using ThreadLocal<SimpleDateFormat>: ThreadLocal is a best appraoch to implement Per Thread Singleton classes or per thread context information.
  2. FastDateFormat.getInstance(): FastDateFormat is available in commons-lang-version.jar. it has several overloaded methods of getInstance() to provide the date format for Thread-safe environment. Please find the API documents here.

Sample code snippet by using SimpleDateFormat:
package com.samples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {
 
 private static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
 
 public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("Current Time: " + dateFormat.format(currentDate));
 }

}



Sample code snippet by using ThreadLocal:
package com.samples;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadLocalDateFormatExample {

 private static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
  protected DateFormat initialValue() {
   return new SimpleDateFormat("MM/dd/yy");
  }
 };
 
 public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("Current Time: " + dateFormat.get().format(currentDate));
 }

}


Sample code snippet by using FastDateFormat:
package com.samples;

import java.util.Date;

import org.apache.commons.lang.time.FastDateFormat;

public class FastDateFormatExample {

 private static final FastDateFormat dateFormat = FastDateFormat.getInstance("dd-MM-yyyy");
 
 public static void main(String[] args) {
  Date currentDate = new Date();
  System.out.println("Current Time: " + dateFormat.format(currentDate));
 }
}

Hence, the best approach is to format the date isby using FastDateFormat if your project has commons-lang.jar dependency, otherwise can use Threadlocal approach.

Wednesday, 5 March 2014

Unix basic commands

Below are the few basic Unix commands which will be more useful for Java developers who are working in Unix environment.

List all users:
cat /etc/passwd |grep "/home" |cut -d: -f1
awk -F":" '{ print "username: " $1 "\t\tuid:" $3 }' /etc/passwd

The above commands will list all the users in the system.

Some Basic commands:
cd path - change directory.
mv path1/filename1 path2/filename2 - Move files from one directory to another directory.
ls [options]- list the file names.
ll [options]- list the file names with permissions and size.
cp path/filename1 path2/filename2 - Copy files from one directory to another directory.
cat filename - To print the content of the file.
diff filenmae1 filename2 - To view the differences between two files.
./filename.sh - To run sh files. This is mostly used for executing shell scripts and server stop start.
view filename - To view the content of the file.
vi filename - To view and update the file.
top - To check the CPU performance and utilization.
df - To check the disk space utilized.

vi & view editor commands:
----------------------------
When a opened a file with vi/view command, the file will open in command mode as default. To make changes in the files needs bring to "Insert Mode".
i/<Ins> - insert text before cursor, until <Esc> hit. Also called "Insert Mode".
I - insert text at beginning of current line, until <Esc> hit
<Esc> - Change to "Command Mode".

:w - saves the current file without quitting
:# - move to line #
:$ - move to last line of file
?string - Search backward for string
/string - Search forward for string
n - move to next occurrence of search string
N - move to next occurrence of search string in opposite direction
<Esc>:w! - Saves the file
<Esc>:q! - Quit editing, no save

Create a .jar file:
$ jar -cvf <file_namer.jar> <class_file_path>

To work with above command, first we need to change the directory to JDK installed bin directory and execute the command.

Ex:
$ /opt/WebSphere7/AppServer/java/bin/jar -cvf calculator.jar com/calc/Calculator.class
$ /opt/WebSphere7/AppServer/java/bin/jar -cvf ibank.jar com/calc/*.class

The second command is useful when there are multiple class to be include in a jar. the path /opt/WebSphere7/AppServer/java/bin is a JDK installed path from whepsher server.


Update a .jar file:
jar -uvf <file_namer.jar> <class_file_path>

Ex:
$ /opt/WebSphere7/AppServer/java/bin/jar -uvf calculator.jar com/calc/Calculator.class
$ /opt/WebSphere7/AppServer/java/bin/jar -uvf calculator.jar com/calc/*.class

Unzar a .jar file:
$ jar -xvf <file_namer.jar>

Ex:
$ /opt/WebSphere7/AppServer/java/bin/jar -xvf calculator.jar
Once the above command executed, we will get the class files in unix files system. So first we need to change the directory where we need the files to be located and provide bin full path while executing the command.
If we not change the directory and executed from JDK installed path, all extracted files will be placed in JDK installed path.

Find a Class file in .jar file:
grep classname *.jar

Ex:
grep com/calc/Calculator.class *.jar
grep Ibank.class *.jar

To Know the package exactly:
$ /opt/WebSphere7/AppServer/java/bin/jar -tvf calculator.jar|grep Calculator*

Check HTTP Server status:
$ ps -efw|grep httpd

File system size:
When we are facing with file system space issue and not able to find which directory occupies more memory, use the below command.

du -sm *| sort -nr | head -15
du -sh * | sort -nr | more

To transfer tar files from one IP to another IP:
Login to the IP address, where the file is available and execute the below command.
$ /usr/local/openssh/bin/scp <path>/<file_name>  <userid>@<ip_address>:/tmp/