Sunday, May 16, 2010

Deep Copy of java object graph

The following method uses serialization to make deep copies and avoid extensive manual editing or extending of classes. Need to make sure that all classes in the object's graph are serializable.

import java.io.*;

public class ObjectCloner {
 // so that nobody can accidentally create an ObjectCloner object
 private ObjectCloner() {
 }

 // returns a deep copy of an object
 static public Object deepCopy(Object oldObj) throws Exception {
  ObjectOutputStream oos = null;
  ObjectInputStream ois = null;
  try {
   ByteArrayOutputStream bos = new ByteArrayOutputStream(); // A
   oos = new ObjectOutputStream(bos); // B
   // serialize and pass the object
   oos.writeObject(oldObj); // C
   oos.flush(); // D
   ByteArrayInputStream bin = new ByteArrayInputStream(bos
     .toByteArray()); // E
   ois = new ObjectInputStream(bin); // F
   // return the new object
   return ois.readObject(); // G
  } catch (Exception e) {
   System.out.println("Exception in ObjectCloner = " + e);
   throw (e);
  } finally {
   oos.close();
   ois.close();
  }
 }

}

Array Copy with Java 6

@Test
 public void genericArrayCopyOf() {
    Number[] source = { new Double(5.0), new Double(10.0) };
    Number[] target = Arrays.copyOf(source, source.length);
    assertEquals(source, target);
 }
 
 @Test
 public void copyOfWithRange() {
    String[] source = { "0", "1", "2", "3", "4" };
    String[] target = Arrays.copyOfRange(source, 2, 4);
    assertEquals(new String[] { "2", "3" }, target);
 }

 @Test
 public void genericArrayCopyOfWithNewType() {
    Number[] source = { new Double(5.0), new Double(10.0) };
    Double[] target = Arrays.copyOf(source, source.length, Double[].class);
    assertEquals(source, target);
 }

Tuesday, May 11, 2010

Parallel class hierarchies with Java Generic


import java.util.ArrayList;
import java.util.Collection;

/*
 * Super class for Habitat hierarchy 
 */
public abstract class Habitat <A extends Animal> {
 
 /*
  * A generic collection that can hold Animal 
  * or any subclass of animal 
  */
 Collection<A> collection = new ArrayList<A>();
 
 /*
  * add an Inhabitant to the collection.
  * should be overridden by subclass
  */
  public abstract  void addInhabitant( A animal);
}
/*
 * Aquarium class inherit the collection from 
 * Habitat superclass. But limit the collection 
 * to Fish type. 
 */
public class Aquarium extends Habitat <Fish> 
{
 
 /*
  * (non-Javadoc)
  * @see Habitat#addInhabitant(Animal)
  */
 @Override
 public void addInhabitant( Fish fish) { 
  collection.add(fish);
     System.out.println(Aquarium.class); 
   } 
}

/*
 * Super class for Animal hierarchy
 */
public abstract class Animal {

}
public class Fish extends Animal {

}
public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Animal animal = new Fish();
  Fish fish = new Fish();
  //new Aquarium().addInhabitant(Animal); -- would cause compiler error
  new Aquarium().addInhabitant(fish);
 }

}

Sunday, May 9, 2010

SQL Windowing

Suppose, we have a "Contract_Transaction" table which keeps a history of transaction of contracts. It actually facilities the General Ledger Entry in the Financial Book. The idea is never to update a transaction, always add a positive or negative $ amount to mimic Debit and Credit. As an example, if a contract-worth $100-is sold, the transaction table would record $100. But if contract is cancelled and $40 is refunded, then record another entry with -$40 for the same contract.

If we like to know the net value of each contract, we just need to do a group by with contract number. But if we like to know the latest status of contract with the net value simple group by won't do it. we need to use the SQL Windowing to achieve that. We not only need sum up each contract but also to rank each row within the contract number by date. Then we only keep the row with latest date or rank 1. Here is an example.

 CREATE TABLE "Contract_Transaction" ( "Contract_Number" int2 DEFAULT NULL,  "Contract_Status" char(1) DEFAULT NULL,  "Contract_Amount" numeric DEFAULT NULL,  "Change_Date" date DEFAULT NULL )  

insert into Contract_Transaction values (1,'Active',100.00, '2010-4-1');
insert into Contract_Transaction values (1,'Cancel',-40.00, '2010-4-3');
insert into Contract_Transaction values (2,'Active', 50.00, '2010-4-2');

 
WITH RNK (Contract_Number,        Contract_Status,        Contract_Amount,        RNK) AS   
( SELECT Contract_Number,      
  Contract_Status,     
  sum(Contract_Amount)  OVER ( PARTITION BY Contract_Number ORDER BY Change_Date ROWS  UNBOUNDED PRECEDING ),      
  RANK()          OVER (PARTITION BY Contract_Number                ORDER BY Change_Date ) 
  FROM Contract_Transaction ) 
SELECT * FROM TMP WHERE RNK = 1