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)

Friday, September 3, 2010

Interruptable Background Processing in C#

I was looking for some Interruptable background processing utility in C#.

Background processing can be done with BackgroundWorker but making it interruptable
was the tricky one. Its not only the threading but handling the events too.

Tried to google it did not find the exact one but some good help.


On any activity (user stops the process or work completes ) signal shall be raised to process the main thread.

Doing the process of actual work can be started in the Thread or Worker Thread in the background asynchronously.
Starting Thread ( in InterruptableBGProcess.InitialiseServiceProcess(...))
in the background.

InterruptableBGProcessing.cs
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
isStopped = false;
            
/* initialise the background processing service */
var serviceControlEvents = InterruptableBGProcess.InitialiseServiceProcess((BackgroundWorker)sender);

/* now simulate a waitstate by waiting until the user click on stop orwork completed. */

while (true)
{
 if (isStopped || ProgressBar.Value == 100)
 {
  break;
 }
}
            
/* signal the event to tell the service to stop, then wait for the event
   to be set which indicates the service has stopped*/

 WaitHandle.SignalAndWait(serviceControlEvents[0], serviceControlEvents[1]);
        
}


Once thread started it will look for the event signals
SignalProcessToStop and ProcessHasCompleted of type AutoResetEvent

/*Initialises the processing controller, process events
 and starts the process.*/
public static WaitHandle[] InitialiseServiceProcess(
BackgroundWorker bg)
{
 var processSvc = new InterruptableBGProcess(bg);
 var thread = new Thread(processSvc.ProcessController);
 thread.Start();
 return new[] { 
    processSvc.SignalProcessToStop, processSvc.ProcessHasCompleted };
}


/* when thread runs... */
private void ProcessController()
{
/* wait on the threads SignalProcessToStop event*/
var wh = new WaitHandle[] { SignalProcessToStop };
while (true)
{
 /* SignalProcessToStop.Set(); 
 if above is done (i.e  set) than waitHandles will not 
receive the signal and loop will break;*/

var fTimedOut = !WaitHandle.WaitAll(wh, 100);
if (fTimedOut && counter != 100)
/* if we timed out, do the processing or 
   work not finished completely*/
  ExecuteWork(); 
else
{
  break; /* thread process was signalled to stop*/
}
}
/* indicate the processing service has stopped, allows 
waiting threads to proceed, if don't set this than main thread 
will not proceed.*/            
ProcessHasCompleted.Set();
}



Download complete example from here: Downlaod Demo InterruptableBackGroundProcessing.rar

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