Monday, 18 July 2016

HashCode and Equals method in Java object

Introduction

Java.lang.Object has methods called hasCode() and equals(). These methods play a significant role in the real time application. However its use is not always common to all applications. In some case these methods are overridden to perform certain purpose. In this article I will explain you some concept of these methods and why it becomes necessary to override these methods.



hashCode()


As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode(); It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.



equals()

This particular method is used to make equal comparison between two objects. There are two types of comparisons in Java. One is using “= =” operator and another is “equals()”. I hope that you know the difference between this two. More specifically the “.equals()” refers to equivalence relations. So in broad sense you say that two objects are equivalent they satisfy the “equals()” condition. If you look into the source code of Object class you will find the following code for the equals() method.

public boolean equals(Object obj)
{
return (this == obj);
}



Now I will explain you when to override the equals() and hashCode() methods and why it is necessary to override these methods. In this regard there is a rule of thumb that if you are going to override the one of the methods( ie equals() and hashCode() ) , you have to override the both otherwise it is a violation of contract made for equals() and hashCode(). Please refer to the Sun’s java docs for the method’s contract. I provide some test case scenario where you will find the significance of these methods. Case-1: You can override the hashCode method in your own way. Please refer to the following example.

package com.core;

/**
* @author
*
*/
public class Emp
{
private int age ;

public Emp( int age )
{
super();
this.age = age;
}

public int hashCode()
{
return age;
}
}

In the above example class “Emp” the variable age is the significant factor. Here the hashCode value will return the age of the person. Now let us consider the following test harness class.

package com.core;

/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
System.out.println("emp1.hashCode()--->>>"+emp1.hashCode());
}
}

If you run the above program, the output will be the age what you have given i.e. 23. Now question arises whether there is any way we can get the original hashCode(). We can say that if we do not override the hashCode() method what could have been the hashCode of this object. However please do not feel depressed, Java provide another approach even if you have overridden the hashCode() method , still you can get the original hashCode of a particular class. Now run the following test harness program.

package com.core;

package com.core;

/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
System.out.println("Overridden hashCode()--->>>"+emp1.hashCode());
int originalHashCode = System.identityHashCode(emp1);
System.out.println("Original hashCode of Emp---->>>"+originalHashCode);
}
}
Here the output will be like this Overridden hashCode()--->>>23 Original hashCode of Emp---->>>22222 As you know the above number is arbitrary, it depends upon your system. So then why it is necessary to override this method. There is one reason that if want to compare two objects based upon the equals() method. Although in a very simple class like “Emp”, you can achieve without overriding hashCode() method. But if you do this , you are going to violate the contract for the methods hashCode() and hashCode() of the object class. The similar case is for the method equals(). So funcational point is that if want to compare two objects based upon the equals() method you have to override both hashCode() and equals() methods. Please have look into the Emp class with the overridden methods and the related test harness class.

package com.core;

/**
* @author
*
*/
public class Emp
{
private int age ;

public Emp( int age )
{
super();
this.age = age;
}

public int hashCode()
{
return age;
}

public boolean equals( Object obj )
{
boolean flag = false;
Emp emp = ( Emp )obj;
if( emp.age == age )
flag = true;
return flag;
}
}

The related test harness class is given below.

package com.core;

/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(23);
System.out.println("emp1.equals(emp2)--->>>"+emp1.equals(emp2));
}
}

Case- 2 Think of a test scenario where you want to store your objects in a HasSet and you want to find a particular object. First let us see if we do not override the methods and we want to store the objects in the HashSet. Let us analyse the impact of it from the following code.

package com.core;

/**
* @author
*
*/
public class Emp
{
private int age ;

public Emp( int age )
{
super();
this.age = age;
}

}

In the above code it is a normal class. Now let us see the test harness class.

package com.core;

import java.util.HashSet;

/**
* @author
*
*/
public class TestEmp
{
public static void main(String[] args)
{
Emp emp1 = new Emp(23);
Emp emp2 = new Emp(24);
Emp emp3 = new Emp(25);
Emp emp4 = new Emp(26);
Emp emp5 = new Emp(27);
HashSet hs = new HashSet();
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
hs.add(emp4);
hs.add(emp5);

System.out.println("HashSet Size--->>>"+hs.size());
System.out.println("hs.contains( new Emp(25))--->>>"+hs.contains(new Emp(25)));
System.out.println("hs.remove( new Emp(24)--->>>"+hs.remove( new Emp(24));
System.out.println("Now HashSet Size--->>>"+hs.size());
}
}

If you run the above program, the will output will be like the following. HashSet Size--->>>5 hs.contains( new Emp(25))--->>>false hs.remove( new Emp(24)--->>>false Now HashSet Size--->>>5 It means that you can not find the object. However it is not the case for Integer object. You can put object of type Integer in a HashSet and you can try and you can see the effect. Now let us modify the “Emp” class so that we will get over the problems what we faced in the above test harness class.


package com.core;

/**
* @author
*
*/
public class Emp
{
private int age ;

public Emp( int age )
{
super();
this.age = age;
}

public int hashCode()
{
return age;
}

public boolean equals( Object obj )
{
boolean flag = false;
Emp emp = ( Emp )obj;
if( emp.age == age )
flag = true;
return flag;
}
}

Here in the above class, we have overridden the hashCode() and equals() methods. Now if you run the same test harness class, you will get the desired output like the following. HashSet Size--->>>5 hs.contains( new Emp(25))--->>>true hs.remove( new Emp(24))--->>>true Now HashSet Size--->>>4 Case – 3 In this case you want to use your object as key not the value in the HashMap. So you have to override both the methods hashCode() and equals(). However it is left to the reader to create the object and test the feature in a Map. Case-4 If want to make your own immutable object , it will be wiser to override the equals() and hashCode() methods. To test the above programs, please create the appropriate package as mentioned in the program. You can also create your own package and modify the package name in the above programs. You can all the code in your favorable java editor.

Friday, 27 June 2014

Javascript date validation

Insert below script into Head


<script LANGUAGE="JavaScript">

<!-- Begin
function isValidDate(dateStr) {
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Date is not in a valid format.")
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}
return true;  // date is valid
}
//  End -->
</script>


Insert below in the body


<center>
<form onSubmit="return isValidDate(this.date.value);">
Your Birth Date:  <input type=text name=date size=10 maxlength=10> (in MM/DD/YYYY format)
<input type=submit value="Submit Date">
</form>
</center>
</div>

Wednesday, 25 June 2014

Number Formatting Using JavaScript

Tested Approach:
number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');Short solution #2:

Alternate Solution:
number.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && !((a.length - i) % 3) ? ',' + c : c;
});

Example:
5543.45 will be converted to 5,543.45.

Wednesday, 21 May 2014

HTTP Request by using JSTL

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
  <head>
    <title>Page Data Example</title>
  </head>
  <body>
    <h3>&#160;</h3>
    <table border="1" width="539">
      <tr>
        <td colspan="2" width="529" bgcolor="#0000FF">
          <b>
            <font color="#FFFFFF" size="4">HTTP
            Request(pageContext.request.)</font>
          </b>
        </td>
      </tr>
      <tr>
        <td width="210">Access Method</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.method}" />
        </td>
      </tr>
      <tr>
        <td width="210">Authentication Type</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.authType}" />
        </td>
      </tr>
      <tr>
        <td width="210">Context Path</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.contextPath}" />
        </td>
      </tr>
      <tr>
        <td width="210">Path Information</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.pathInfo}" />
        </td>
      </tr>
      <tr>
        <td width="210">Path Translated</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.pathTranslated}" />
        </td>
      </tr>
      <tr>
        <td width="210">Query String</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.queryString}" />
        </td>
      </tr>
      <tr>
        <td width="210">Request URI</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.requestURI}" />
        </td>
      </tr>
    </table>
  </body>
</html>

Wednesday, 14 May 2014

Reading xls and xlsx in java using POI jars

Below Jars are Required for implemnetation:
   dom4j-1.6.1.jar
   poi-3.10-FINAL-20140208.jar
   poi-ooxml-3.10-FINAL-20140208.jar
   poi-ooxml-schemas-3.10-FINAL-20140208.jar
   stax-api-1.0.1.jar
   xmlbeans-2.3.0.jar
   commons-lang-2.6.jar

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelMainProgram {
 public static void main(String[] args) throws Exception {
  //
  // An excel file name. You can create a file name with a full path
  // information.
  //
  System.out.println(new Date());
  String filename = "Template.xls";//xls or xlsx
  //
  // Create an ArrayList to store the data read from excel sheet.
  //
  ArrayList<ArrayList<Cell>> sheetData = new ArrayList<ArrayList<Cell>>();
  FileInputStream fis = null;
  try {
   //
   // Create a FileInputStream that will be use to read the excel file.
   //
   fis = new FileInputStream(filename);
   //
   // Create an excel workbook from the file system.
   //
   Workbook workbook = WorkbookFactory.create(fis);;
   //
   // Get the first sheet on the workbook.
   //
   Sheet sheet = workbook.getSheetAt(0);
   //
   // When we have a sheet object in hand we can iterator on each
   // sheet's rows and on each row's cells. We store the data read
   // on an ArrayList so that we can printed the content of the excel
   // to the console.
   //
   Iterator<Row> rows = sheet.rowIterator();
   while (rows.hasNext()) {
    Row row =rows.next();
    if(row.getRowNum()==2)
    {continue;}
   }
   while (rows.hasNext()) {
    Row row =rows.next();
    Iterator<Cell> cells = row.cellIterator();
    System.out.println(row.getRowNum());
    ArrayList<Cell> data = new ArrayList<Cell>();
    while (cells.hasNext()) {
     Cell cell =  cells.next();
     data.add(cell);
    }
    sheetData.add(data);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (fis != null) {
    fis.close();
   }
  }
  showExelData(sheetData);
  System.out.println(new Date());
 }
 private static void showExelData(List<ArrayList<Cell>> sheetData) {
  //
  // Iterates the data and print it out to the console.
  //
  for (int i = 0; i < sheetData.size(); i++) {
   List<Cell> list = (List<Cell>) sheetData.get(i);
   for (int j = 0; j < list.size(); j++) {
    Cell cell =list.get(j);
    cell.setCellType(Cell.CELL_TYPE_STRING);//To get the cell value as string set the cell type as String
    System.out.print(cell.getStringCellValue() + "\t\t");
    if (j < list.size() - 1) {
     //System.out.print("SPACE");
    }
   }
   System.out.println("");
  }
 }
}

JavaScript/Ajax file upload with Jquery iframe post

Demo code
<script type="text/javascript" src="jQueryAjaxUpload.js"></script>

<form method="post" action="" enctype="multipart/form-data" id="example_form">
<input type="file" name="file"/>
<input type="submit"/>
</form>
<script>

$('#example_form').ajaxUpload({

post :
function (){

alert('posted');
},


complete :
function() {

alert('Upload complete');
}


});
</script> In case of using spring add below bean to spring beans
<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- one of the properties available; the maximum file size in bytes -->

<property name="maxUploadSize" value="1000000"/>
</bean>
 Follow the below link to download jQueryAjaxUpload.js file

http://www.jainaewen.com/files/javascript/jquery/iframe-post-form.html

Monday, 3 February 2014

Create a Simple Spring MVC application along with Java Script or JQuery Datatables

The main reason for writing this tutorial is i found many examples online but all are either very basic or more complicated(i felt) so i wanted to share my knowledge in creating a sample spring MVC application that will display some data using JQuery Datatables.


Prerequisites :

        To do this tutorial we need to have any version eclipse that have an option to create dynamic web project and Apache Tomcat or Similar Server to run the application.
         

 Step by Step Procedure:
  1.  Lets start creating a dynamic web project by name Spring3MVC as shown in below image.
   


 2. Once we create the dynamic web project we have the skeleton for web app, we need to add the jars under lib folder of WEB-INF required for Spring that are mentioned in the Jars Required Section .

  3. You need to add the below entries in your web.xml to configure theDispatcher servlet of spring 

<display-name>Spring3MVC</display-name>
            <servlet>    <servlet-name>spring</servlet-name>    <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup>          </servlet>         <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.action</url-pattern>       </servlet-mapping>


 if you observer the above XML code servlet name is specified as spring  which means  the spring container will search for the spring-servlet.xml  for loading the beans and other spring specific configurations.

4.  Create a file with name spring-servlet.xml  under WEB-INF folder and copy the below XML content to that file.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

 <context:component-scan base-package="com.sample.spring3mvc.controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="productFacade"
  class="com.sample.spring3mvc.facade.impl.ProductFacadeImpl">
 </bean>
 <bean id="productDao"
  class="com.sample.spring3mvc.dao.impl.ProductDaoImpl">
 </bean>
 <mvc:annotation-driven />
 <mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  </mvc:message-converters>
</mvc:annotation-driven>
</beans>

5. Explanation of Entries in spring-servlet.xml
     <context:component-scan base-package="com.sample.spring3mvc.controller" /> : This entry will tell spring container where  the controller classes are available, all the files/packages under the above package will scanned for controllers.
   viewreolver bean  used to configure the prefix path and suffix extension of the views returned, so that we dont need to return these values in controller.
  <mvc:annotation-driven> : This entry is required if we are going to use any annotations in the bean classes. For example @Autowired.
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  </mvc:message-converters> 
         The above entry is required for automatic conversion of normal objects to JSON when @Responsebody is used in any of the controller method which we will see in the later parts of the tutorial.
  The rest of the entries are just beans that we gonna use in application.

With this we are done with the configuration part and now we jump into real coding stuff.

Java and JSP Coding

  Create a index.jsp and place it under WebContent/webroot folder and the content would be something like this.

<html>
<head>     <title>Spring 3.0 MVC Series: Index - </title> </head> <body>     <a href="home.action"> Home</a> </body> </html>
    The below jsp would be a simple one if you do not want the Datatable in it.
 Create home.jsp under Web-INF/pages with the below content
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<link
href="//datatables.net/download/build/nightly/jquery.dataTables.css"
rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script> <meta charset=utf-8 /> <title>Spring MVC -DataTables Example</title> </head> <body> <div class="container"> <h2>Directly Loaded Data and added Datatable after load</h2> <table id="example" class="display" width="100%"> <thead> <tr> <th align="left">Name</th> <th align="left">Color</th> <th align="left">Price</th> </tr> </thead> <tfoot> <tr> <th align="left">Name</th> <th align="left">Color</th> <th align="left">Price</th> </tr> </tfoot> <tbody> <c:forEach items="${products}" var="product"> <tr> <td>${product.name}</td> <td>${product.color}</td> <td>${product.price}</td> </tr> </c:forEach> </tbody> </table> </div> <div class="container"> <h2>Loaded Data through ajax after page Load</h2> <table id="example1" class="display" width="100%"> <thead> <tr> <th align="left">Name</th> <th align="left">Color</th> <th align="left">Price</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> </body> <script> $(document).ready(function() { var table1 = $('#example').DataTable(); var table2 = $('#example1').DataTable({ "ajax" : "${pageContext.request.contextPath}/getAllProds.action", }); }); </script>
</html>


If you observe in the above code we are directly referencing the javascript files it works only if u have internet connection. If you have downloaded those javascript files you can refer it locally as well.


Datatable usage in Spring Explanation

In the above jsp code i gave two examples for Datatable                  I. Applying Datatable to already loaded HTML table with id example1, the js code for this is as simple as $('#example').DataTable();                 II. In the second case we are directly loading data using an ajax call associated with Datatable which is  $('#example1').DataTable({ "ajax":"${pageContext.request.contextPath}/getAllProds.action"});                  but for doing the above step the data returned from the controller should be in a particular form of JSON as suggested in the site, which is done using getJSONForProd  method in the controller and returning aaData  from the controller.               For Live Examples on Datatables you can go here Live Datatables Example.
Controller Code    Create a Controller with name HomeController.java and use the below code.    ProductData is just a POJO .
   productFacade.getAllProducts() will return list of ProductData  which u can just mock it.
package com.sample.spring3mvc.controller;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sample.spring3mvc.data.ProductData;
import com.sample.spring3mvc.facade.ProductFacade;


@Controller
public class HomeController {

    @RequestMapping("/home")
    public ModelAndView helloWorld(final Model model) {
        model.addAttribute("products",productFacade.getAllProducts());
        return new ModelAndView("home", "message", model);
    }
    @Autowired
 private ProductFacade productFacade;
 
    @ResponseBody
    @RequestMapping("/getAllProds")
 public Map<String, Object[]> getAllProducts()
 {
     List<ProductData> aaData= productFacade.getAllProducts();
  return Collections.singletonMap("aaData", getJSONForProd(aaData));
 }
  
    /**
     * I only want certain product info..
     */
     public Object[] getJSONForProd(Collection<ProductData> prods){
         Object[] rdArray = new Object[prods.size()];
         int i = 0;
         for(ProductData u:prods){
             // [ name, id,arn,groups ]
             Object[] us = new String[]{u.getName(),u.getColor(),Double.toString(u.getPrice())};
             rdArray[i] = us;
             i++;           
         }
         return rdArray;
     }
}

Run the application on server
  Once all the above steps are completed successfully you run the application by right clicking on the application as shown below
Run on server
Once you run you can see the associated server will start and then you can key in the below link in any of the qualified browser ex:Chrome and test: http://localhost:8080/Spring3MVC/


In case of any doubts/clarifications/Suggestions you are welcome @vinaytaj2006@gmail.com



Run Postman API remote or code or command line

POSTMAN is used to run the APIs generally. What if we want to create a collection in postman and run it from some other code or command l...