Wednesday, September 14, 2011

Remote Debugging In Eclipse

Remote debugging capability with different debuggers( IDEs) are nice features for developers. Purpose of this blog is to share this information that how to use remote debugging tools effectively. Here i tried to give example for eclipse IDE.

Remote debugging in eclipse can be done in two ways:
a) Socket Attach
b) Socket Listen


Socket Attach: For e.g. we want to debug an application which is deployed on tomcat and we want to debug that. Attach the application process through eclipse once we start our tomcat in debug mode.

Step 1:
How to start tomcat in debug mode:
$./catalina.sh jpda start (in case of unix based machines) or
> catalina.bat jpda start ( in case of windows based machines)

This is going to start a tomcat in debug mode and a socket with port as 8000 can be attached to it.
In case if user wants to attach to different port than following can be done.
export JPDA_ADDRESS=8000  (in case of unix based machines)
$./catalina.sh jpda start


set JPDA_ADDRESS=8000 (in case of windows based machines)
> catalina.bat jpda start

Step 2:
Open debug configuration on eclipse and add new Remote Java Application.
Connection Type should be Standard (Socket Attach). Give a host name or ip in the value for Host in connection properties where the remote process is running.
For e.g.

















For Other application server like WebSphere:
Open admin console and open Servers->Server Type -> WebSphere Application Servers.
Than choose your server from the list of available servers. And than select Debugging service.
for e.g:
Application servers > server1 > Debugging service
Make check box "Enable service at server startup" as selected.
default port for debug is 7777, change it if you want to debug on different port.
Restart the server and attach your debugger ( IDE or eclipse) to it.


Socket Listen: When we want to start a listener first and the remote application is required to be attached to the eclipse
debugger, in that case. First we need to start the eclipse debugger in Socket Listten mode and attach the application.

Step 1:
Open debug configuration in eclipse and add new Remote Java Application.
Connection Type should be Standard (Socket Listen).
Port in connection properties should be 8000 if you want remote application should connect using this port value.
For e.g.
















Step 2:
Options a) if wants to debug with ant than in your build.xml add
<jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,server=n" /> for e.g.
<target name="execute" description="Test">
  <java classname="${main.class}" fork="true" failonerror="true">
   <classpath refid="class.path" />
   <arg value="${myargument}" />
   <jvmarg value="${myjvmargument}" />
   <jvmarg value="-Xrs" />
   <jvmarg line="-Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,server=n" />
  </java>
</target>

     
Option b) If you wants to debug with .bat file or on command prompt

Java -Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000 -jar MyJar.jar


Options c) if you wants to debug a application which is again an eclipse ( or eclipse based plugins) than you can start the eclipse application as


eclipse.exe -vmargs -Dosgi.requiredJavaVersion=1.6 -Xms256m -Xmx512m -Xdebug -Xrunjdwp:transport=dt_socket,address=10.240.1.14:8000,suspend=n

10.240.1.14 IP where you want to debug and where your debugger is running.
Debugging in JBoss can be debugged by modifying JAVA_OPTS in the file which is used to start the server in the similar way as mentioned above.
IBM WebSphere is already explained above.

Friday, June 24, 2011

Dynamic Proxy for gui component listener using InvocationHandler.

Listeners for gui is always easy to create and difficult to maintain.
As they will create additional classes for that and in case we need to
give a patch or something it can be a real pain.

Lets say that a Frame (MyFrame.java) has 10 components and each of them has a listener than there will be 10 additional classes ( MyFrame$1.class,... , MyFrame$10.class, etc).
Now if a fix is given for one of the component and we really do not know which one to give as a hot fix, we will be ending up in giving all the 11 classes.
Another thing which might also force to give all the classes if we change the serialversionId.

So how to overcome this, i have tested it and found it works well.
But is it the right thing to do not sure but good to know.

We can use the InvocationHandler to handle this situation which can call the required method of the frame where we can have the logic/code to be run using Dynamic Proxies to call whenever event is raised.


import java.lang.reflect.*;

/**
 * @author deepak.singhvi
 *
 */
public class InvocationHandlerProxy implements 
      InvocationHandler {

private Object obj;

public static Object newInstance(Object obj) {
  return Proxy.newProxyInstance(obj.getClass()
  .getClassLoader(), obj.getClass().getInterfaces(),
  new InvocationHandlerProxy(obj));
}

public InvocationHandlerProxy(Object obj) {
 this.obj = obj;
}

public Object invoke(Object proxy, Method m, Object[] args)
 throws Throwable {
 Object result;
  try {
    result = m.invoke(obj, args);
  } catch (InvocationTargetException e) {
    throw e.getTargetException();
  } catch (Exception e) {
    throw new RuntimeException("unexpected invocation exception: "
 + e.getMessage());
  } 
  return result;
}
}


For every gui component, for e.g. button instead of overriding actionListener for some action event we can call.

ActionListener foo = (ActionListener) InvocationHandlerProxy.newInstance(new FooWithoutArgActionListener(this,"methodWithoutArgument",new Class[0]));

Listener class would implement ActionListener as usual but the method to be called when a
specific event is raised will be defined in the same class where listener is created, without creating lister anonymously.

public class FooWithoutArgActionListener 
implements ActionListener {
  Method method;
  Object parent;
  public FooWithoutArgActionListener(Object classObject, 
    String methodName, Class[] parameterTypes ){
    method = getTargetMethod(classObject, methodName, parameterTypes);
    this.parent = classObject;
}

@Override
public void actionPerformed(ActionEvent e) {
 ....
  method.invoke(parent, new Object[0]);
 ...
}

private Method getTargetMethod(Object target,
  String methodName, Class[] parameter) 
{
// find the target method which should get 
// executed when actionPerformed is called.
}


Click here to get the Complete example

Saturday, June 4, 2011

Find from which jar a class was loaded

In order to find at runtime where from file system a class was loaded, following command would be useful:

System.out.println(<myjavaclassname>.class.getProtectionDomain().getCodeSource().getLocation());

Output will be something like this:
file:/C:/TestWorkSpace/lib/MyLibrary.jar

It can be helpful while debugging some class loading problems.

Friday, March 11, 2011

Hibernate and DAO

UNDER CONSTRUCTION


package com.dao;

public interface DAOIntf<T> {
public void update(T obj);
public void save(T obj);
public void delete(T obj);
}





package com.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.util.HibernateUtil;



public class AbstractDAOImpl<T> implements DAOIntf<T>{

  @Override
  public void update(T obj) {
    save(obj);
  }

  @Override
  public void save(T obj) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      session.save(obj);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  }

  @Override
  public void delete(T obj) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = null;
    try {
      transaction = session.beginTransaction();
      session.delete(obj);
      transaction.commit();
    } catch (HibernateException e) {
      transaction.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
  
   }

}



ProductDAOIntf.java
package com.dao;

import java.util.List;

public interface ProductDAOIntf<T> extends DAOIntf<T> {
  public T getProductByID(int id);
  public List<T> getAllProducts();
}


ProductDAOImpl.java
package com.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.hbm.Product;
import com.util.HibernateUtil;



public class ProductDAOImpl<T> extends AbstractDAOImpl<T> implements ProductDAOIntf<T> {

  @Override
  public T getProductByID(int id) {
  Session session = HibernateUtil.getSessionFactory().openSession();
    T product=null;
    try {
      product =(T) session.get(Product.class,id);  
    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return product;
  }
 
  @Override
    public List<T> getAllProducts(){
    Session session = HibernateUtil.getSessionFactory().openSession();
    List<T> list = null;
    try {
      list = session.createQuery("from Product").list();
    } catch (HibernateException e) {
      e.printStackTrace();
    } finally {
      session.close();
    }
    return list;
  }

}


Product.java
package com.hbm;

import java.io.Serializable;

public class Product implements Serializable {
 
 
  public Integer getProduct_Id() {
    return Product_Id;
  }

  public void setProduct_Id(Integer product_Id) {
    Product_Id = product_Id;
  }

  public String getProduct_Name() {
    return Product_Name;
  }

  public void setProduct_Name(String product_Name) {
    Product_Name = product_Name;
  }

  public Double getProduct_Price() {
    return Product_Price;
  }

  public void setProduct_Price(Double product_Price) {
    Product_Price = product_Price;
  }

  public Integer getProduct_QOH() {
    return Product_QOH;
  }

  public void setProduct_QOH(Integer product_QOH) {
    Product_QOH = product_QOH;
  }

  Integer Product_Id;
  String Product_Name;
  Double Product_Price;
  Integer Product_QOH;

  @Override
    public String toString() {
      return "Id : " + Product_Id + "\t Name " + Product_Name + "\tQOH " + Product_QOH;
    }
}

Product.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

  <class name="com.hbm.Product" table="product" >
   <id name="Product_Id" type="int"> <generator class="identity"></generator></id>
   <property name="Product_Name" type="string" length="50" />
   <property name="Product_Price" type="double" lazy="true" />
   <property name="Product_QOH" type="int"/>
   
  </class>
</hibernate-mapping>

Tuesday, December 14, 2010

Thread Working For Fixed Time Even In Case Of Exceptions (UncaughtExceptionHandler)

Somebody asked me how to keep running a thread for a fixed interval even there is some exception.
At that point of time i had no answer.

But now i think, i have the answer.

And this can be done using the interface Thread.UncaughtExceptionHandler.

UncaughtExceptionHandler is an inner interface of Thread class.

We can implement it and set it using the method setUncaughtExceptionHandler() of Thread class.

Here is an example.

class MyThread extends Thread {
 
private boolean flag; 
protected int counter=0;
MyThread(int counterInitialValue) {
   this.counter = 0;
}

public MyThread(Runnable r,int counterInitialValue) {
   super(r);
   this.counter = counterInitialValue;
   this.flag = true;
}

@Override
public void run() {
 if (!flag) {
 flag = true;
 System.out.println("Thread Exec Started");
 } else {
 System.out.println("Thread Running Again");
 }
 while (counter <20) {
  counter++;
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
// do some work here....
  if(counter % 3 == 0){
    System.out.println(" Thread working , 
          counter value is : "+ counter);
  }
  if (counter == 10) {
   throw new RuntimeException("I am throwing exception");
  }
   
  }
 }
}

class MyThreadExceptionHandler implements 
        Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, 
                              Throwable e) {
  MyThread oldThread = (MyThread) t;
  System.out.println("Received exception "+ 
                           e.getMessage());
  if (oldThread.counter < 20) 
  {
   System.out.println("Value of counter 
       (restart required) : " + oldThread.counter);
   
   MyThread newThread = new MyThread(oldThread,11);
   
   newThread.start();
  } 
  else 
  {
   System.out.println("Thread work done");
   System.out.println("Value of counter : " +
                       oldThread.counter);
  }
 }
}



public class ThreadRunningForFixedTime {
public static void main(String[] args) {
  MyThread th = new MyThread(0);
  MyThreadExceptionHandler handler = 
          new MyThreadExceptionHandler();
  th.setUncaughtExceptionHandler(handler);
  th.start();
 }
}

Monday, December 6, 2010

How to make a non-serializable class serializable

I have a class which is not serializable. If i will try to serialize the object of it than i am going to get exception "java.io.NotSerializableException"

And now if this class is not not modifiable/available to modify (may be its a third party), and so we do not have any control.

for e.g following is the non serializable class
class MyNonSerializableClass {
 String str = new String("mystring");
 MyNonSerializableClass(){
  
 }
 MyNonSerializableClass(String s) {
  this.str = s;
 }

 public String getStr() {
  return str;
 }

 public void setStr(String str) {
  this.str = str;
 }

}



In order to serialize the object we can write a wrapper class over MyNonSerializableClass and which is implementing Serializable interface.
And the most important thing, we control the readObject and writeObject methods so that we can decide what need to be written with the wrapper class.

something like this:

class MyNonSerializableClassWrapper extends MyNonSerializableClass implements Serializable {
 MyNonSerializableClassWrapper(){
  super();
 }
 MyNonSerializableClassWrapper(String s) {
  super(s);
 }

 private void writeObject(ObjectOutputStream out) throws IOException {
  // not required the default write object
  // ----> out.defaultWriteObject();
  out.writeObject(super.getStr());
 }

 private void readObject(ObjectInputStream in) throws IOException {
  // not required the default read object
  // ----> in.defaultReadObject();
  try {
   super.setStr((String) in.readObject());
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }
}


As the wrapper class itself does not have any properties/attributes so defaultread and write is not required.
By getting the super class value and setting it during the write and read to serialized object we can achieve the serialization and deserialization even if a class is not implementing Serializable interface.


private void WriteObjectToFile() {
try {
  FileOutputStream fo = new FileOutputStream("c:\\test.ser");
  ObjectOutputStream os = new ObjectOutputStream(fo);
  os.writeObject(new MyNonSerializableClassWrapper("This is a test of 
                                           serialization"));
  fo.close();

  } 
  catch (FileNotFoundException e) {
    e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  }
}


private void ReadObjectFromFile() {
try {
  FileInputStream fi = new FileInputStream("c:\\test.ser");
  ObjectInputStream in = new ObjectInputStream(fi);
  MyNonSerializableClassWrapper mw = (MyNonSerializableClassWrapper) 
  in.readObject();
  fi.close();
  System.out.println("serialized object value is: " + mw.getStr());
  } 
  catch (FileNotFoundException e) {
      e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  } 
  catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
}




Tuesday, November 30, 2010

XML Writing with Java DOM Parser

I am looking for something like this kind of xml.


Some of the things in very short about the DOM parsers
1. Tree of nodes
2. Memory: Occupies more memory, preffered for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy
6. Ease of navigation

DOM which builds a data tree in memory for easier, non-sequential access to XML data fragments.

Now lets jump directly to the example.

******CREATE DOCUMENT OBJECT******

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DB docB = dbf.newDocumentBuilder();
Document doc = docB.newDocument();
******POPULATE DOCUMENT DATA******

// create the root and child tags
// create root node with the name company
Element root = doc.createElement("company");

//create a employee element
Element parent= doc.createElement("employee");

// set empid which is attribute of the element
parent.setAttribute("empid","E1");

// create child element for parent and add a textnode to it.
Element child = doc.createElement("firstname");
child.appendChild(doc.createTextNode("Deepak"));

// append the child "first name" to the parent "employee"
parent.appendChild(child);

******SAVE DOCUMENT TO FILE******
// write into the file
TransformerFactory tfac = TransformerFactory.newInstance();
Transformer transformer = tfac.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);

StreamResult streamResult = new StreamResult(new File("c:/text.xml"));

transformer.transform(source, streamResult);



Download complete example from here: Downlaod Demo Write-Read-Modify Example (Eclipse Project)

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...