Sunday, June 10, 2012

Java Decompiler (Jad) : A Smart guide

Jad is a command line Java decompiler written by Pavel Kouznetsov,written for several plateform.
can be downloaded from
1. http://www.kpdus.com/jad.html
2. http://www.varaneckas.com/jad

Installation is very easy,just extract the downloaded zip .
Set the environment variable path for your plateform here I am using windows.
After setting the path variable open the cmd to check the proper installation type jad on
command prompt,if every thing goes fine you will find the fallowing outupt.








To decompile single java class use the command
jad -sjava MyClass.class

To decompile Multiple java class use the command
jad -o -r -sjava -dsrc bin/**/*.class

Jadclipse plugin for Eclipse
Download the Jadclipse for eclipse from http://sourceforge.net/projects/jadclipse/
Copy the extracted jars in the Eclipse plugin folder.
Restart the Eclipse and set the decompliler path as shown









Now your Eclipse is ready to decompile any java class whose source file is not provided with you,just press
F3 on the name of the class and see the magic.

Ant Build File to decompile all the classes inside the jar

<project name="Decompile_jars" default="main" basedir=".">


<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>


<property name="jad" location="c:/program files/jad1.5.8/jad.exe"/>
<property name="unjar.dir" location="loc_unjar"/>

<target name="main">
    <input
        message="Please enter jar file name"
        addproperty="input.file"
        defaultvalue="source"
    />

    <!-- clean temp dir -->
    <delete dir="${unjar.dir}"/>

    <!-- unpack jar file -->    
    <unjar src="${input.file}.jar" dest="${unjar.dir}"/>

    <!-- decompile all class files -->
    <exec executable="cmd.exe">
        <arg line="/c ${jad} -o -r -sjava -d${unjar.dir} ${unjar.dir}/**/*.class"/>
    </exec>     
     
    <!-- create jar file -->
    <jar destfile="${input.file}_decompile.jar">
        <fileset dir="${unjar.dir}"
            excludes="**/*.class"
        />
    </jar>

    <!-- clean temp dir -->
    <delete dir="${unjar.dir}"/>
    
</target>


</project>

Spring Framework and SL4J Integration

The Simple Logging Facade for Java or (SLF4J) serves as a simple facade or abstraction for various logging frameworks, e.g. java.util.logging, log4j and logback, allowing the end user to plug in the desired logging framework at deployment time.

slf4j is actually not a logging library - it's just a facade. You choose a logging framework by yourself. We use slf4j and logback that implements the slf4j API natively.

The SLF4J project has similar goals to commons-logging. It uses quite a different approach, however, which has both benefits and drawbacks. Future versions of commons-logging may adopt some of the concepts of SLF4J.

Spring uses Jakarta Common Library(JCL) and java.util.logging,SL4J has advantages over JCL as it does not suffer
from class loader problem and Memory Leak Problem.SLFJ for logging in java use parametrized version of various log methods they are faster as compared to normal method.


Lests Demonstrate the Integration of SL4J to String framework,in this example we are using SL4J with logback framework

Step 1: Create Java Project.
Step 2: Add Spring Library,SL4J jars and Logback jars in build path as shown





Step 3: Create a class which includes logger as fallows
package com.main;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloSl4j {
 
 private static final Logger logger = LoggerFactory.getLogger(HelloSl4j.class);
 
 public void sayHello(){
  logger.info("Inside the sayHello Method");
  System.out.println("Say Hello To Spring SL4J Integration");
 }
}




Step 4: create the spring.xml for your application context as shown


 

 



Step 5: create your logger.xml to configure logging as fallows
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
 
 <appender name="STDOUT"
            class="ch.qos.logback.core.ConsoleAppender">
 
    <!-- encoders are assigned by default the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
    <encoder>
   <pattern>
    %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
   </pattern>
    </encoder>
  </appender>
 
 <root level="INFO">
  <appender-ref ref="STDOUT" />
 </root>
 
</configuration>

Step 6: Create your main class fallows

package com.test;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.main.HelloSl4j;

public class HelloSl4jTest {

 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  HelloSl4j helloSl4j = (HelloSl4j) ctx.getBean("helloSl4j");
  helloSl4j.sayHello();
 }

}


Here is the Logging Console





Saturday, June 9, 2012

Working with Java SE 7 Exception Changes

Working with Java SE 7 Exception Changes

Jelastic : A better Cloud Hosting Solution for Java

Lets try Jelastic Cloud hosting solution which is far better and easier solution than Google App Engine.
The other cloud hosting Solution which are getting popular these days are Cloud Foundry and OpenShift.
i am not going to compare all these hosting solution but try to getting started with Jelastic which
offer a very user friendly UI to setup your application environment.
I am trying to setup my small application on the Jelastic platform its not that tough as I was thinking it
the http://jelastic.com/ home page is self explanatory how you should start from.

lets setup our application environment by selecting JDK 6,Tomcat 6 and MongoDB as our NoSQL database,choose
your hosting provide and signup for free








Login with the password sent by jelastic to your registered mail address
provide enviornment name and press create









After pressing the create button jelastic takes some time to configure your enviornment and send the MongoDB
node details to your registered mail id open the RockMongo (MongoDB web UI) with the help of provided userid and password.

Setup MongoDB configuration like database name,collection name etc with the help of GUI.








After Deploying the application Test you application on http://testap.jelastic.servint.net/view/index.jsp
And MyApp is up and Running








Spring : Working with JdbcTemplates

Spring provides JDBC Templates to access the data from the database with ease.Spring provides
org.springframework.jdbc.core.JdbcTemplate which basically take cares about all your
connection establishment to the database post query work eg closingh statement and connections.

Merits of spring templates as compared to conventinal Data access through JDBC
1. Connection Handling is done by Spring container you need not to worry about it,by this way
it reduced the singnificant amount of the coding.
2. Exception handling in conventional data access through JDBC is very cumbersome process,
here Spring take care of all these stuff by converting SQLException to the RuntimeException
3.ResultSetExtractor or RowMapper which allows result directl into the Object ResultSetExtractor
or a list of objects RowMapper.

Lets have a walk through how to work with JdbcTemplates

Step 1: Create your database as fallows,Here I am using MySQL as database.




Step 2: Create the Java Project and add Spring framework jar library to it.
Step 3: Create spring.xml as shown



 
 
 
 
  
  
  
  
  
  
 
 




Step 4:
Create Employee Model Class as shown
package com.example.model;

public class Employee {
 
 private int empid;
 private String empName;
 
 public Employee(int empid,String empName){
  this.empid = empid;
  this.empName = empName;
 }
 
 public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 

}

Step 5:Create the Data Access Object as fallows
package com.example.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.example.model.Employee;
@Component
public class EmpDaoImpl {
 
 @Autowired
 private DataSource dataSource;
 
 public void create(int empid, String employee_name) {
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  jdbcTemplate.update("INSERT INTO EMPLOYEE (empid, EMPLOYEE_NAME) VALUES(?,?)",
    new Object[] { empid, employee_name });
 }
 
 public DataSource getDataSource() {
  return dataSource;
 }

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

}

Step 6: Create your main class as fallows to check whether all these things are in right shape.
package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.dao.EmpDaoImpl;
import com.example.model.Employee;

public class Main {
 
 public static void main(String[] args) {
  
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  EmpDaoImpl empdl = ctx.getBean("empDaoImpl",EmpDaoImpl.class);
  
  empdl.create(1, "Sharad Singh");  
  
  System.out.println("Data Inserted In Database");
 }

}

Output @ console:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Data Inserted In Database

Step 7:
Look into the database table whether data has been updated or not,Here you go......






Friday, June 8, 2012

Spring : Working with DataSource and Database Connection Pooling

Getting Database connection through conventional JDBC is very tedious task which include a lot
Exception handling and repeative coding,Spring simplifies the whole process with very ease.
Spring provides the org.springframework.jdbc-3.1.0.RELEASE.jar whic contains the org.springframework.jdbc.datasource.DriverManagerDataSource to get the connection
object to the Database.

For the production environment we can use org.apache.commons.dbcp to implement the connection
pooling,here I summarize how we implement the connection pooling in spring framework.
Step 1: The very first step is to create the Java project and add the Spring Library as fallows







Step 2:Setup the database,in this example i am using MySQL as a database,ensure MySQL database driver jar
should be in the class path.
Step 3:Crate the spring.xml file in source folder as fallows

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

 <context:annotation-config/>
 <context:component-scan base-package="com.example"/>
 
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/HibernateDb"/>
  <property name="username" value="root"/>
  <property name="password" value="root"/>
  <property name="initialSize" value="2"/>
  <property name="maxActive" value="5"/>
 </bean>
 

</beans>

Step 4: Create your Model Class as fallows
package com.example.model;

public class Employee {
 
 private int empid;
 private String empName;
 
 public Employee(int empid,String empName){
  this.empid = empid;
  this.empName = empName;
 }
 
 public int getEmpid() {
  return empid;
 }
 public void setEmpid(int empid) {
  this.empid = empid;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 

}

Step 5: create DataAccessor Object to get the data from database

package com.example.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.model.Employee;
@Component
public class EmpDaoImpl {
 
 @Autowired
 private DataSource dataSource;
 
 public Employee getEmployee(int empid) throws Exception{
  
  Connection conn = null;
  conn = dataSource.getConnection();
  PreparedStatement ps = conn.prepareStatement("select * from employee where empid = ?");
  ps.setInt(1, empid);
  
  Employee emp = null;
  ResultSet rs = ps.executeQuery();
  
  if(rs.next()){
   emp = new Employee(empid, rs.getString("employee_name"));
  }
  rs.close();
  ps.close();
  
  return emp;
  
  
  
 }

 public DataSource getDataSource() {
  return dataSource;
 }

 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }

}

Step 6: Now test your prog by using your Main Class as shown

package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.dao.EmpDaoImpl;
import com.example.model.Employee;

public class Main {
 
 public static void main(String[] args) {
  
  ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
  EmpDaoImpl empdl = ctx.getBean("empDaoImpl",EmpDaoImpl.class);
  
  Employee emp = null;
  try {
   emp = empdl.getEmployee(1);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println(emp.getEmpName());
 }

}
Output






Thursday, June 7, 2012

Convert JSON to DBObject

Conversion of JSON to DBObject need JSON parsing only here I attach the simple
code to understand it.
package com.test;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

public class ConvertJSON2DBObject {
 public static void main(String[] args) {
  try {
   Mongo mongo = new Mongo("localhost",27017);
   DB db = mongo.getDB("myDBName");
   DBCollection collection = db.getCollection("myCollectionName");
   
   //convert JSON to DBObject
   DBObject dbObject = (DBObject) JSON.parse("{'empName':'Rajkumar Singh','emppId':62990}");
   collection.insert(dbObject);
   
   DBCursor cursor = collection.find();
   
   while(cursor.hasNext()){
    System.out.println("OBJ IS : "+cursor.next());
   }
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (MongoException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

}