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

Tuesday, July 6, 2010

C# LogViewer using FileSystemWatcher

I was facing a problem to get the new log message in the Message Log screen.
FileSystemWatcher which was introduced in .net 2.0 make it very easy to develop Message Log Viewer.

1) Create the FileSystemWatcher and set its properties.



            FileSystemWatcher_Log_1.Path = Directory.GetParent("C:\\temp").FullName;
            FileSystemWatcher_Log_1.Filter = "MyLogFile.log";
            NotifyFilters notifyFileters = new NotifyFilters();
            notifyFileters = notifyFileters | NotifyFilters.LastWrite;
           // You can choose other notification filters


            FileSystemWatcher_Log_1.NotifyFilter = notifyFileters;
            FileSystemWatcher_Log_1.EnableRaisingEvents = true;


2) Set the event handler.




            this.FileSystemWatcher_Log_1.Changed += new 
            System.IO.FileSystemEventHandler(this.FileSystemWatcher_Changed);

3) Update GUI when event occours


            // create stream writer only once so that whenever new log is appended in the log file,
           // only that text will be shown in the list view (or which ever the gui component you are using).
            if (null == sr_Log_1)
            {
                sr_Log_1 = new StreamReader(new FileStream(SelectedFileName_Log1_textbox.Text, 
                FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true);
            }
            string line;
            while (sr_Log_1.EndOfStream != true)
            {
                line = sr_Log_1.ReadLine();
                if (line.Trim().Length == 0)
                {
                    continue;
                }
                Log_1_listBox.Items.Add(line);
                Log_1_listBox.TopIndex = Log_1_listBox.Items.Count - 26 + 1;
                
            }



Refer the code for details.
You can download demo code from here here.
It may not be 100% bug free code.

Sunday, July 4, 2010

Learning art of Mocking by EasyMock

Continuing my earlier post about testing and mocking.
Here is the details about EasyMock.


Download presentation here (ppt)

Or

Here ( google docs)

The Art Of Mocking / Test using Mock Objects .

Quality assurance exists in many products, including software.
Software manufacturers perform software testing to ensure the correctness, completeness and quality of their products.

And the testing should also go with hand in hand along with development.
Find out more about testing and mocking in the provided link.

Click here to get the presentation from the link











Testing is an art. :-)

How to change from Windows Authentication to SQL Server Authentication (2005)

Durng installation of SQL Server 2005 i did not care for SQL Server Authentication and installed it Windows Authentication.
And later other users in the network could not use it for the guest account due to some problem.

Here are the steps if you need to add SQL Server Authentication also for SQL Server.


1) Run the following query to enable SQL Server Authentication using MS SQL Server Management Studio (after login as windows authentication)

"ALTER LOGIN sa ENABLE".

2) Set the password for the sa account 
 "ALTER LOGIN sa WITH PASSWORD = 'sa1234"
Password should be strong enough else it will not be accepted and query will fail.

3) Stop the SQL Server service
 Right click on My Computer -> Manage , Computer Management window will open.
Select Service and Applications -> Services -> all the services which start from SQL and stop them.

4) Change in registry
click on Start  -> Run and Enter regedit press enter.
Registry Editor will be opened
Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\LoginMode
and change the value to 2 (Hexadecimal), if its not 2.


5) Restart all services of SQL Server 2005 or restart your machine.

Wednesday, June 30, 2010