Tuesday, July 26, 2011

Difference between Jsp:forward and jsp:include

When you do jsp:forward, pageContext.forward() method is invoked with the given jsp or html resource. When you do jsp:include, JspRuntimeLibrary.include() method is getting invoked. jsp:forward means, browser will show only the resource given as an input to jsp:forward. No new HttpServletRequest and HttpServletResponse objects are created hence all parameters/attributes in HttpServletRequest are passed to the new resource as well. jsp:forward does not change the Url in the browser but HttpServletResponse.sendRedirect() changes the url as well since the request is redirected to the browser and coming back to the servlet/action class.

Monday, June 27, 2011

Debugging a JBoss application

Recently had a chance to debug a Jboss application through eclipse. Below are the steps I did.

1. JBoss version is 6.0.0.
2. edited <JBossHome>/bin/run.conf.bat and added the below line
set "JAVA_OPTS=%JAVA_OPTS% -Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
3. Started jboss server and got the below print
Listening for transport dt_socket at address: 8000
4. Then in the eclipse, select the project and then Run ----> Debug Configurations-----> Remote Java Application. On the right side, select the project, and set the connection type as Standard (Socket Attach), Host as localhost and give port as 8000. Click on Debug.
5. Then select Window ----> Show View ---> Debug, you will be able to see the stack traces.
6. Most of the standalone debugging operations i.e setting a break point, adding a watch would work in remote debugging also.

Friday, June 24, 2011

Dead Lock Example

How to create dead lock?  Here is the fine example.
Lets talk about money transfer from one account to another account. Money has to be debited from one account and it has to be credited into another account.


public class Transfer extends Thread
{
           private Credit credit  = null;
           private Debit debit = null;
           private boolean odd = false;

           public Transfer(Credit credit, Debit debit,boolean odd)
           {
                       this.credit=credit;
                       this.debit=debit;
                      this.odd=odd;
            }

            public void run()
            {
                       if(odd)
                      {
                                transferMethod1();
                       }
                       else
                       {
                                 transferMethod2();
                        }
             }

            //first lock credit and then do debit
           public void transferMethod1()
           {
                 credit.credit();
                 //thread.sleep() can be added just to ensure that dead lock is happening
                 debit.debit();
           }

          //first lock debit and then do credit
          public void transferMethod2()
          {
                   debit.debit();
                   //thread.sleep() can be added just to ensure that dead lock is happening  
                  credit.credit();
          }

          public static void main(String a[])
          {
                      Credit c = new Credit();
                      Debit d  = new Debit();
                      Transfer t1 = new Transfer(c,d,true);                     
                      Transfer t2 = new Transfer(c,d,false);
          }
}

class Credit
{
public synchronized credit()
{
//credit implementation
}
}

class Debit
{
public synchronized debit()
{
  //debit implementation
}

When thread t1 calls transferMethod1(), credit object is locked and its waiting for debit object. At the same time, when thread t2 calls transferMethod2(), debit object is locked and its waiting for credit object. t1 can proceed when t2 releases debit object and t2 can proceed when t1 releases credit object. Hence program hangs. One way to avoid this deadlock is, combine those two resources. i.e synchronize both these credit and debit operations. i.e in other words synchronize methods in Transfer object. Make transferMethod1() and transferMethod2() methods synchronized.

Sunday, June 5, 2011

Regex to find Email

Wrote a regular expression to find e-mail which has below conditions.

1. User name must start with a character.
2. It can contain _-. characters but not two consequetive hypens (--). It can contain numbers.
3. Domain name must start with a character or a number it can have any number of subdomains i.e .co.in etc

(\b[a-zA-Z][\w\.^[--]]*)@([a-zA-Z][\w^[--]]*)(\.[\w^[--]]+)+

My idea is to group email as username,domainname. First lets take username. This can be identified by (\b[a-zA-Z][\w^[--]]*).

\b means it should start with a word boundary. It should start with a character, so the character class [a-zA-Z] confirms the same.  Then it could contain any number of characters but not two hypens which can be achieved by a word character \w (a-zA-Z0-9) and a character class ^[--].
Email can have any number of sub domains i.e .co.in. so I split it as (.\w) i.e a . followed by a word character. And the rest is self explanatory.

Thursday, May 19, 2011

Some real world java examples

Just thought about some real world examples.

1. Polymorphism:

In simple terms polymorphism means one interface - multiple implementations. Users can choose the
implementation based on their own interests. For example Vehicle could be the interface and travel
is the method. There could be n number of implementations for Vehicle interface. i.e Van, Car, Bus etc.
Uses can choose their own Vehicle implementation based on their need i.e capacity, cost etc. Polymorphism can
be used for grouping.

2. Inheritance:

In object oriented programming, users can map real world entities into java objects. Through inheritance
parent object's properties are passed to children object properties. This reduces the amount of code
to be written and also increases the maintainability of the code. For example employee is the class that could
have details as name, id, start date of employment, address etc. Also Lead is also an employee but he has
more details as module he owns, review permission etc. Manager is also an employee who has additional responsibilites
like performance review etc., along with the default employee details.

3. Encapsulation:

Encapsulation means providing right access details for the right entities. For example in a hotel,customers are not allowed
inside cooking room. Servers are not allowed inside owner's cabin.

4. Queue:

Queue means first in first out. Railway booking counters.

4. Stack:

Stack means last in first out. Assume a movie theatre has 1000 seats which has only one gate in which people are allowed based on the seat number. Once the
show is over person who sat in 1000th seat, can come out as a first person.

5. Deque:

Deque means addition/removal is supported on both ends. Same theatre example could be applied here where it has two gates. One front gate and one back gate, visitors are allowed in both the gates.

Monday, May 16, 2011

ClassCastException while trying to cast to the same object

Recently I wanted to know how application servers are reloading jsp file.  So thought of finding it myself. Tried writing a ClassLoader that extends java.lang.ClassLoader which always loads class files from the disc and not from the memory.

public class PrintObj
{
         public void print()
         {
                  System.out.println(" one ");
          }
}


public class MyClassLoader extends ClassLoader
{
           public Class findClass()
           {
                      //load it from the disc and return the Class object 
            }
}


public class ClassLoaderTest
{
       public static void main(String a[])
       {
                 ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
                 //it loads it from the memory
                  PrintObj l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
                  l1.print();
                 

                 MyClassLoader loader = new MyClassLoader();   
                 PrintObj l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
                 l2.print();
                 

        }
}

When I am trying to execute the below code, it throws
Exception in thread "main" java.lang.ClassCastException: PrintObj cannot be cast to PrintObj. Bolded line shows ClassCastException. Interested to know that it collides with the existing PrintObj loaded by the system class loader. Then had to create an interface call Print and then made PrintObj implements that Print interface.

public interface Print
{
       public void print();
}


public class PrintObj implements Print
{
       System.out.println(" one ");
}


After doing the above change below code runs with out any problem.

ClassLoader sysLoader = DynamicClassLoader.class.getClassLoader();
//it loads it from the memory
Print l1 = (PrintObj)sysLoader.loadClass("PrintObj").newInstance();
l1.print();

MyClassLoader loader = new MyClassLoader();   
Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
l2.print();


Now other issue when I tried to load the class second time it throws ,

MyClassLoader loader = new MyClassLoader();   
 Print l2 = (PrintObj)loader.loadClass("PrintObj").newInstance();
  l2.print();

 Print l3 = loader.loadClass("PrintObj").newInstance();

Exception in thread "main" java.lang.LinkageError: loader (instance of  MyClassLoader): attempted  duplicate class definition for name: "PrintObj". Then finally realized that a new ClassLoader() instance has to be created to reload a class every time from the disc. 

Monday, April 25, 2011

Writing an Ant Task

Many are having a need to write their own ant task, just like I had. I wanted to search some strings in a set of files and write the result into some destination files. Just listing the steps to achieve the same.

1. I work with Eclipse. Created a Java project and created the below build.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="Search" basedir="." default="jar">

    <target name="clean" description="Delete all generated files">
        <delete dir="classes"/>
        <delete file="search.jar"/>
    </target>

    <target name="compile" description="Compiles the Task">
        <javac srcdir="src" destdir="classes"/>
    </target>

    <target name="jar" description="JARs the Task" depends="compile" >
        <jar destfile="search.jar" basedir="classes"/>
    </target>
  
</project>

2. Wrote a Java code which extends Task class. I wanted to have sourceFile, destFile and searchString as parameters and hence having three  instance variables as sourceFileString, destFileString and searchString.  On execute() method functionality has been implemented.

import org.apache.tools.ant.Task;
import java.io.*;

public class SearchTask extends Task {
   
    private String sourceFileString = null;
    private String destFileString = null;
    private String searchString = null;
   
    public void setSourceFile(String sourceFile)
    {   
        this.sourceFileString = sourceFile;
        System.out.println(" Source file set to "+sourceFile);
    }
   
    public void setDestFile(String destFile)
    {
        this.destFileString = destFile;
        System.out.println(" dest file set to "+destFile);
    }
   
    public void setSearchString(String searchString)
    {
        this.searchString = searchString;
        System.out.println(" search string set to "+searchString);
    }
   
    public void execute()
    {
        System.out.println(" Execute called ");
        File sourceFile = new File(sourceFileString);
        if(sourceFile.isDirectory())
        {
            File[] array = sourceFile.listFiles();
            for(int i=0;i<array.length;i++)
            {
                File file = array[i];
                search(file);
            }
        }
        else
        {
            search(sourceFile);
        }
    }
   
    private void search(File sourceFile)
    {
        System.out.println(" searching starts ");
       
        BufferedReader reader = null;
        BufferedWriter writer = null;
       
        try
        {
            reader = new BufferedReader(new FileReader(sourceFile));
            writer = new BufferedWriter(new FileWriter(destFileString));
            String line  = null;
           
            while( (line = reader.readLine()) != null)
            {
                System.out.println(" line =="+line+" searchString "+searchString);
                if(line.indexOf(searchString) > -1)
                {
                    writer.write(line);
                    writer.newLine();
                }
            }
        }
        catch(Exception ee)
        {
            ee.printStackTrace();
        }
        finally
        {
            try
            {
                writer.close();
                reader.close();
            }
            catch(Exception ee)
            {
                ee.printStackTrace();
            }
        }
    }
}


3. Executed jar task and created search.jar. Then added the below task.

<target name="search" depends="jar" description="searching the file">
        <taskdef name="search" classname="SearchTask" classpath="search.jar"/>
        <search sourceFile="e:\\searchFile.txt" destFile="e:\\searchresult.txt" searchString="cool" >
        </search>

</target>