Friday, February 21

Heuristic exceptions






Heuristic exceptions are inconsistent exceptions . These exceptions does not come all the time and May occur suddenly due to some unavoidable condition 







For example You are calling a service to do some transaction on database and data-source configuration is missing . This happened because last time server got restarted Data-source configuration is removed . So this can be restored by setting the configuration right. 

For example in distributed system multiple parties taking part in a two phase commit transaction are waiting for transaction manager to get information If all of them should commit their individual transaction or not. Transaction manager took lot of time to response and Participant committed their individual transaction even before that . There could come a situation where some participants commit their transaction while others don't and they rollback it if transaction manager sends information to rollback. Thus in distributed system data becomes highly inconsistent .
You put some message in JMS queue But all of a sudden Queue connection breaks and you fail you get any proper response .

Such kind of strange and inconsistent exception falls under heuristic exceptions.


-->

Thursday, February 20

Creating a zip file in java

Creating a zip file in java 




Converting a String into a test file and putting that in zip file 


  1. Here I am creating File.zip file at location D:/file.zip
  2. Here two text files are using by reading an existing txt file
  3. One Pdf file is created by reading an existing file
  4. One txt file is created from a String 
  5. All are zipped together and are put in zip file 




import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class Zipper {
    
    public static void main( String[] args )
    {
      byte[] buffer = new byte[1024];

      try{

        FileOutputStream fos = new FileOutputStream("D:\\File.zip");
        ZipOutputStream zos = new ZipOutputStream(fos);
        ZipEntry ze= new ZipEntry("spy.txt");
        zos.putNextEntry(ze);
        FileInputStream in = new FileInputStream("D:\\spy.txt");

        int len;
        while ((len = in.read(buffer)) > 0) {
          zos.write(buffer, 0, len);
        }

        in.close();
        
        ZipEntry ze1= new ZipEntry("spy1.txt");
        zos.putNextEntry(ze1);
        FileInputStream in1 = new FileInputStream("D:\\spy.txt");

        int len1;
        while ((len1 = in1.read(buffer)) > 0) {
          zos.write(buffer, 0, len1);
        }

        in1.close();
        
        ZipEntry ze2= new ZipEntry("Promote PDF.pdf");
        zos.putNextEntry(ze2);
        FileInputStream in2 = new FileInputStream("C:/Users/mkum63/Desktop/Promote PDF.pdf");

        int len2;
        while ((len2 = in2.read(buffer)) > 0) {
          zos.write(buffer, 0, len2);
        }

        in.close();
        
        
        ZipEntry ze4= new ZipEntry("spy4.txt");
        zos.putNextEntry(ze4);
        StringBuilder sb=new StringBuilder();
        sb.append("dfdgfdgf");
        sb.append("\n");
        sb.append("dsfsdfs");
        sb.append("/n");
        sb.append("dsfsfsdfdffdf");

        InputStream  in4 = new ByteArrayInputStream(sb.toString().getBytes());
                
        int len4;
        while ((len4 = in4.read(buffer))>0) {
          zos.write(buffer, 0, len4);
        }
          
        in4.close();
        
        zos.closeEntry();

        zos.close();

        System.out.println("Done");

      }catch(IOException ex){
         ex.printStackTrace();
      }
    }
}




Wednesday, December 4

Iterator Design Pattern

Iterator design pattern in java

Lets write an class that has method next() and hasNext() which basically are backbone for iterator design pattern

This Iterator will be iterating over a collection represented by Collection class

Collection class consist of an array of elements that Iterator will be iterating over.

Additionally methods to add and remove elements from array are also available in Collection class

IteratorTestor class consist of all the scenarios where in




  1. First we are iterating over existing list of elements
  2. Then few elements are added to the array and It is again iterated over
  3. Then few elements are removed from the array and then It is again iterated over

Here is the Well compiled code to try this via java code

-=========================================================


public interface Iterator {
   
    public Object next();
    public boolean hasNext();

}


=========================================================


public interface Container {
   
    public Iterator getIterator();

}

=======================================================

This class consist of an inner class MyIterator which basically becomes the part of collection class and
thus it becomes easy for MyIterator class to work on variables of enclosing class. 


import java.lang.reflect.Array;

public class Collection implements Container {

    public
    String[] list = {"element1", "element2", "element3", "element4" };

    public int index;

    @Override
    public Iterator getIterator() {
        // TODO Auto-generated method stub
        return new MyIterator();
    }
   
    public void addElement(Object obj){
        int arrLength=list.length;
        arrLength++;
        String[] newArr =new String[arrLength];
        newArr[arrLength-1]=obj.toString();
        System.arraycopy(list, 0, newArr, 0, list.length);
        list=new String[newArr.length];
        System.arraycopy(newArr, 0, list, 0, newArr.length);


    }
   
    public void removeElement(Object obj){
        int arrLength=list.length;
        arrLength--;
        String[] newArr =new String[arrLength];
        System.arraycopy(list, 0, newArr, 0, list.length-1);
        list=new String[newArr.length];
        System.arraycopy(newArr, 0, list, 0, newArr.length);


    }


    private class MyIterator implements Iterator {

        @Override
        public Object next() {
            // TODO Auto-generated method stub
            if (hasNext()) {
                return list[index++];
            }
            return null;
        }

        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub
            if (list.length > index) {
                return true;
            }
            return false;
        }

    }

}

============================================================








public class IteratorTester {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Collection repo = new Collection();

        while (repo.getIterator().hasNext()) {
            System.out.println(repo.getIterator().next());
        }

        System.out.println("=================Lets Add Few More Elements========================");

        repo.index=0;
        repo.addElement("NewElemen1");
        repo.addElement("NewElemen2");
        repo.addElement("NewElemen3");
        while (repo.getIterator().hasNext()) {
            System.out.println(repo.getIterator().next());

        }
        System.out.println("===============Lets Remove few elements==========================");

        repo.index=0;
        repo.removeElement("Elemen1");
        repo.removeElement("Elemen2");
        while (repo.getIterator().hasNext()) {
            System.out.println(repo.getIterator().next());

        }


    }
}
===================================================






And this program will print below logs on console :


++++++++++++++++++++++++++++++++++++++++

element1
element2
element3
element4
=================Lets Add Few More Elements========================
element1
element2
element3
element4
NewElemen1
NewElemen2
NewElemen3
===============Lets Remove few elements==========================
element1
element2
element3
element4
NewElemen1

+++++++++++++++++++++++++++++++++++++++

Monday, December 2

Coding Practice to avoid error while using Object references






Let's understand this by example


import java.util.Date;

import java.util.Date;

public class Refree {

    public static void main(String args[]) {

        Date date = new Date();
        Dater coach = new Dater(date);
        System.out.println(coach.date);
        date.setYear(1111);
        System.out.println(coach.date);

    }

}

class Dater {
    public Date date;

    Dater(Date date) {
        this.date = date;
    }
}








This program will print

Mon Dec 02 16:33:48 IST 2013
Mon Dec 02 16:33:48 IST 3011


But in line date.setYear(1111); we only want to change the value of date and not coach instance But this code is changing values of date as well as coach.

So how can we avoid that :

Let's see another version of same program


import java.util.Date;

public class Refree {

    public static void main(String args[]) {

        Date date = new Date();
        Dater coach = new Dater(date);
        System.out.println(coach.date);
        date.setYear(1111);
        System.out.println(coach.date);

    }

}

class Dater {
    public Date date;

    Dater(Date date) {
        this.date = new Date(date.getTime());
    }
}




-->

This program will print

Mon Dec 02 16:36:36 IST 2013
Mon Dec 02 16:36:36 IST 2013



So that's what we wanted..

Command Design Pattern

Consider yourself a referee of a race where you need to give below commands to athletes

Ready -- Athlete to get ready for race
Set  ---
Athletes to all set to run
Go  ---
Athletes to run the race

How can we automate this in java using command design pattern .





Lets consider there is a Race class which defines there action


public class Race {

    public void getReady() {

        System.out.println("getting ready");
    }

    public void set() {
        System.out.println("setting running position");

    }

    public void go() {
        System.out.println("running");

    }
}



Now we need to create there command classes for these three actions

Let's create an interface first which basically will be uniformly implemented by all there command classes

Interface name is Position. It is declaring single method execute()


public interface Position {

    public void execute();
}







Next there command classes

Ready , Set and Go


public class Ready implements Position {

    Race race;   
    public Ready(Race race){
        this.race=race;
    }
    @Override
    public void execute() {

        race.getReady();

    }
}



public class Set implements Position {

    Race race;   
    public Set(Race race){
        this.race=race;
    }
   
    @Override
    public void execute() {
        race.set();
    }

}


public class Go implements Position {

    Race race;   
    public Go(Race race){
        this.race=race;
    }
   
    @Override
    public void execute() {
        race.go();

    }

}



-->


Every command class has one argument constructor which allows Command instances set Race class instance to execute the method on Race class.

Now it is duty of Referee to pass instance of Race class to Commands and Commands will execute() the method invoked inside execute() method.

Here is Referee class


public class Referee {

    public static void main(String args[]){
        Race race=new Race();
       
        Position position1=new Ready(race);
        Position position2=new Set(race);
        Position position3=new Go(race);
       
        position1.execute();
        position2.execute();
        position3.execute();

       
        }

}


Put together all these classes and execute program as java application. That will print below logs on console :



getting ready
setting running position
running