Tuesday, September 24, 2013

Bitwise Shift operators in java with code

Java provides bit wise shift operation only on integral types (int, long, possibly short and byte or char).

There are 3 types of bit wise shift operators.

1) >> (Signed right shift operator)

It will shift the bit pattern of the first argument to the right by the number of positions mentioned in the second argument.  It fills in positions on the left with zeros. It keeps the sign of the argument unchanged.

           
Example
Meaning In Binary format
Result
2 >>1
10  should be shifted to right by 1 position (keep the sign unchanged)
1
-2 >> 1
10  should be shifted to right by 1 position (keep the sign unchanged) 
-1


Byte representation (8 bytes)
2 >> 1
1
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1

-2 >> 1
-1
1
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
Red color to indicate sign


This operator gives the value which is equal to the integer division by 2^n where n is the number of positions.

2) << (Signed left shift operator)

It will shift the bit pattern of the first argument to the left by the number of positions mentioned in the second argument. It fills in positions on the right with zeros.
 It keeps the sign of the argument unchanged.

Example
Meaning In Binary format
Result
2 << 1
10  should be shifted to left by 1 position (keep the sign unchanged)
4
-2 << 1
10  should be shifted to left by 1 position (keep the sign unchanged) 
- 4


Byte representation (8 bytes)
2 << 1
4
0
0
0
0
0
0
1
0
0
0
0
0
0
1
0
0

-2 << 1
-4
1
0
0
0
0
0
1
0
1
0
0
0
0
1
0
0
Red color to indicate sign


This operator gives the value which is equal to the integer multiplication by 2^n where n is the number of positions.

3)  >>> (Unsigned right shift operator)
It shifts bit pattern of the first argument to the right by the number of positions mentioned in the second argument without caring what the original sign was. It fills in positions on the left with zeros.

Byte representation (8 bytes)
2 >>> 1
1
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1

-2 >>> 1
65
1
0
0
0
0
0
1
0
0
1
0
0
0
0
0
1
Red color to indicate sign

This operator works differently based on the sign of the first argument. It does not keep the sign of the argument. (Which means it may change) .In case of Positive numbers it works just like a signed right shift operator. For negative numbers this operator produces a positive value.

Java code to test the shift operators is below. (Please note that the code below uses 32 bytes since integer is used)

public class BitOperatorsExample {
public static void main(String[] args) {
int i = 2;
int negi = -2;
int leftShiftPositive = i << 1;   // 20
int leftShiftNegative = negi << 1;  // -4
int rightShiftPositive = i >> 1;  // 2
int rightShiftNegative = negi >> 1; // -1
int UnsignedRightShiftPositive = i >>> 1; //1
int UnsignedRightShiftNegative =  negi >>> 1; //2147483647
System.out.println(Math.pow(2, 31));
System.out.println("leftShiftPositive :"+ leftShiftPositive);
System.out.println("leftShiftNegative :"+ leftShiftNegative);
System.out.println("rightShiftPositive :"+ rightShiftPositive);
System.out.println("rightShiftNegative :"+ rightShiftNegative);
System.out.println("UnsignedRightShiftPositive :"+ UnsignedRightShiftPositive);
System.out.println("UnsignedRightShiftNegative :"+ UnsignedRightShiftNegative);
}
}

Monday, April 15, 2013

Source code to create a simple hibernate application


This post helps you to create an application to perform basic  DB operations using hibernate framework. The intent of posting this blog is to provide working source code to perform simple DB CRUD operations. The code provided here uses Mysql database and hibernate without annotations.

Before starting with the coding part make sure that you have added required libraries to your workspace. If not please download it from websites below.
      1)     Hibernate jar location: http://sourceforge.net/projects/hibernate/files/hibernate3/3.1.3/
      2)      Add the Mysql jars depending upon the version of Mysql. I am using mysql 5. (ex: mysql-connector-java-5.1.24.jar,mysql.jar)

Steps to perform basic DB operations:
       1)      Prepare the configuration
       2)      Build the session factory from configuration
       3)      Open the session from session factory
       4)      Begin the transaction using session.
       5)      Perform DB operations
       6)      Commit the transaction
       7)      Close the session

Using the transaction is not mandatory here.But it is a good practice.

Project structure:

Create the following mappings and code.
1       1)      Create an object class (which has to be persisted).
2       2)      Create a mapping file to map between the object and DB table.
         3)      Create a configuration for hibernate.
         4)      Create a class to perform the database operations mentioned above.



    hibernate.cfg.xml :
   Add the connection properties and the other resources such as mapping files.




<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
   <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/HibDB</property>
    <property name="connection.username">root</property>
    <property name="connection.password">pass123</property>
    <mapping resource="com\sabhahit\mapping\Student.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

    Student.hbm.xml :

   Add the mapping between the object and the database tables.Primary key of the table should be mentioned as part of id.

     <?xml version="1.0" encoding="utf-8"?>

    <!DOCTYPE hibernate-mapping PUBLIC 
     "-//Hibernate/Hibernate Mapping DTD//EN"
     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 


    <hibernate-mapping>
   <class name="com.sabhahit.objects.Student" table="Student" lazy="false">
      <meta attribute="class-description">
         This class contains the Student detail. 
      </meta>
      <id name="studentID" type="int" column="studentID">
         <generator class="increment"/>
      </id>
      <property name="name" column="name" type="string"/>
      <property name="grade" column="grade" type="string"/>
      <property name="standard" column="standard" type="int"/>
      <property name="dateOfBirth" column="dateOfBirth" type="date"/>
    </class>
   </hibernate-mapping>


    Student.java
    It is the Bean class/object which should be persisted.

      package com.sabhahit.objects;


      import java.util.Date;




      public class Student {
public Student()
{
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
public int hashCode() {
return super.hashCode();
}
private int studentID;
private String name;
private String grade;
private int standard;
private Date dateOfBirth;

public int getStudentID() {
return studentID;
}
public void setStudentID(int studentID) {
this.studentID = studentID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int getStandard() {
return standard;
}
public void setStandard(int standard) {
this.standard = standard;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

     }


         BasicCRUDOperations.java

        This is the class which has methods to perform all the basic DB Operations.
         
          package com.sabhahit.utils;


import org.hibernate.HibernateException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.sabhahit.objects.Student;

public class BasicCRUDOperations {


private static SessionFactory factory;

static String INSERT ="Insert";
static String UPDATE ="Update";
  static String DELETE ="delete";
  static String READ = "select";

public static Student doCRUDOperations(Student student,String Operation)
{
Session session = null;
Transaction tx = null;
Student st = null;
try{
session = factory.openSession();
tx = session.beginTransaction();

if(Operation.equalsIgnoreCase(INSERT)){
session.save(student);
}else if(Operation.equalsIgnoreCase(UPDATE)){
session.update(student);
}else if(Operation.equalsIgnoreCase(DELETE)){
session.delete(student);
}else if(Operation.equalsIgnoreCase(READ)){
st =(Student) session.load(Student.class, new Integer(student.getStudentID()));
}

tx.commit();

return st;
}catch (HibernateException e) {
System.out.println("Exception while Performing "+ Operation);
e.printStackTrace();
tx.rollback();
return null;
}finally{
session.close();
}
}

public static void getSessionFactory()
{
Configuration cfg = new Configuration();
cfg.configure("com\\sabhahit\\databaseConfig\\hibernate.cfg.xml");
factory = cfg.buildSessionFactory();
}
   }

           FirstHibernateApp.java

         This class uses the methods in the   BasicCRUDOperations.java to perform DB operations.

          package com.sabhahit.utils;


import java.text.ParseException;

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


import com.sabhahit.objects.Student;


public class FirstHibernateApp {


public static void main(String[] args) {

BasicCRUDOperations.getSessionFactory();
 
//Create a new Student
Student st = new Student();
st.setName("Demon");
st.setStandard(1);
st.setGrade("A");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date dob;
try {
dob = sdf.parse("20/08/1978");
st.setDateOfBirth(dob);
} catch (ParseException e) {
e.printStackTrace();
}
BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.INSERT);

//Update Student details
st.setName("Monster");
BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.UPDATE);

//Get Student details
Student rdSt =BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.READ);
System.out.println(rdSt.getName() + rdSt.getStudentID());
//Delete Student with id=1 details
st.setStudentID(1);
BasicCRUDOperations.doCRUDOperations(st, BasicCRUDOperations.DELETE);

}


}



     Create the student table as per below.
          


         




Now you can run the application from FirstHibernateApp class.You can see all the DB operations executing without any issues.
        
        Please share your comments if this post has helped you to create your first hibernate application.Happy learning :)


      





Sunday, April 14, 2013

Resolve the error org.hibernate.MappingException: Unknown entity


I was facing this issue when I started implementing my first hibernate application. I have tried to find the solution over the technical forums. But I could not really get the answer which has fixed the issue. So I am posting the solution which would help you too. Reason: hibernate.cfg.xml does not have the resource mapping where the entity mapping is done.
 


Resolution: Add the mapping file name (where entity mapping is done) to the hibernate.cfg.xml .Highlighted in red color below.
 
   <session-factory>
   <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/HibDB</property>
    <property name="connection.username">root</property>
    <property name="connection.password">pass123</property>
    <mapping resource="com\sabhahit\mapping\Student.hbm.xml"/>
  </session-factory>
 



 Stractrace:org.hibernate.MappingException: Unknown entity: com.sabhahit.objects.Student                at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:514)                at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1302)                at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:89)                at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:186)                at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)                at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)                at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)                at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)                at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:530)                at org.hibernate.impl.SessionImpl.save(SessionImpl.java:518)                at org.hibernate.impl.SessionImpl.save(SessionImpl.java:514)                at com.sabhahit.utils.BasicCRUDOperations.doCRUDOperations(BasicCRUDOperations.java:30)                at com.sabhahit.utils.FirstHibernateApp.main(FirstHibernateApp.java:31) 

Monday, June 25, 2012

Java script code to find the difference between 2 dates in terms of months

Its easy to find the month difference in Java since java supports calendar objects.
But java script supports Date objects but not calendar objects.
Here is a code for finding the month difference in javascript.

function getMonthsDifference(firstDate,lastDate)
{
 var date1DtParse = Date.parse(lastDate);
 var date2DtParse = Date.parse(firstDate);
 var date1 = new Date(date1DtParse);         
 var date2 = new Date(date2DtParse);

 var diffYears = date2.getFullYear()-date1.getFullYear();
 var diffMonths = date2.getMonth()-date1.getMonth();
 var diffDays = date2.getDate()-date1.getDate(); 
 var months = (diffYears*12 + diffMonths);
 if(diffDays>0)
 {     months += '.'+diffDays; }
 else if(diffDays<0)
 {     months--;    
 months += '.'+(new Date(date2.getFullYear(),date2.getMonth(),0).getDate()+diffDays);
 }
 return months;
}

Thursday, May 24, 2012

Resolve error "org.springframework.beans.factory.BeanCreationException: Error creating bean with name Hello': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Method must not be null"

I think every Spring beginner will face this issue.Have no clues,Code seems like perfect.Tried all possible ways to resolve it? 

see below!

Reason: Its because of using different versions of the spring jars in the project.

Resolution:
 Clean the libraries/jars added to the project.Remove all the libraries from the class path.Then add the libraries into the project from the same version of Spring.
You can find the libraries in the Spring website  

Make sure that all the libraries added in the project are from the same spring version/release.

Stacktrace:
Nested in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: Method must not be null:
java.lang.IllegalArgumentException: Method must not be null
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.core.BridgeMethodResolver.findBridgedMethod(BridgeMethodResolver.java:63)
    at org.springframework.beans.GenericTypeAwarePropertyDescriptor.<init>(GenericTypeAwarePropertyDescriptor.java:58)
    at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:250)
    at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:144)
    at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:252)
    at org.springframework.beans.BeanWrapperImpl.getPropertyDescriptorInternal(BeanWrapperImpl.java:282)
    at org.springframework.beans.BeanWrapperImpl.isWritableProperty(BeanWrapperImpl.java:333)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1247)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:515)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:362)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
   

Resolve "Target runtime Apache Tomcat v6.0 is not defined." error

Go to window ->preferences ->Server->Runtime environments . add server Apache Tomcat v6.0 Mention the directory where apache-toma...