Sunday, September 29, 2013

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-tomact server is placed

Please find the links to similar errors below.
how-to-remove-default-workspace
resolve-unbound-classpath-container-jre
resolve-target-runtime-apache-tomcat

Resolve Unbound classpath container: 'JRE System Library [jdk1.5.0_06]'/similiar error in project

when an existing dynamic web project is imported into another workspace you may get this error.
Reason:
JRE System Library jdk1.5.0_06 is not available in the project workspace.
Resolution:
a)Add the Library jdk1.5.0_06 in the project
Go to window ->preferences ->Java ->Installed JREs.Add a Standard VM with
JRE name jdk1.5.0_06
b)Create a new dynamic web project in the workspace and add the files from existing project
into the new project created.

Please find the links to similar errors below.
how-to-remove-default-workspace
resolve-unbound-classpath-container-jre
resolve-target-runtime-apache-tomcat

How to remove the default workspace in the RAD/Eclipse?

If you have selected some workspace as deafult by checking the “use this as the default and do not ask again” option when Workspace is loaded,then the same workspace gets loaded everytime you open the RAD/Eclipse.

Use the following steps to remove the default work space :
 Step 1 : Select window-> Preferences-> Select StartUp and Shutdown option in preferences.
 Step 2 : Check the option Prompt for workspace on startup and click on Apply and Ok buttons
Now you will be asked to select the workspace every time you try to open the workspace

Please find the links to similar errors below.
resolve-unbound-classpath-container-jre
resolve-target-runtime-apache-tomcat

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 :)


      





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...