package hirondelle.web4j.model;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import junit.framework.TestCase;

/**
 Test several classes that implement end user messages.
 <P>This test class is unusual, in that it is meant for several target classes, not one.
 */
public final class TESTMessageSerialization  extends TestCase {

  /** Run the test cases.  */
  public static void main(String args[]) {
    String[] testCaseName = { TESTMessageSerialization.class.getName() };
    junit.textui.TestRunner.main(testCaseName);
  }

  public TESTMessageSerialization( String aName) {
    super(aName);
  }
  
  
  public void testAppResponseMessage() throws FileNotFoundException, IOException, ClassNotFoundException  {
    AppResponseMessage arm = AppResponseMessage.forSimple("Test");
    testSerializable(arm);
    arm = AppResponseMessage.forCompound("Test", "param1");
    testSerializable(arm);
    arm = AppResponseMessage.forCompound("Test", "param1", new Integer(56));
    testSerializable(arm);
    //fails, since StringTokenizer is not Serializable
    //arm = AppResponseMessage.forCompound("Test", "param1", new Integer(56) , new StringTokenizer(""));
    //testSerializable(arm);
  }
  
  public void testMessageListImpl() throws FileNotFoundException, IOException, ClassNotFoundException {
    MessageListImpl mli = new MessageListImpl();
    testSerializable(mli);
  }
  
  public void testAppException() throws FileNotFoundException, IOException, ClassNotFoundException {
    AppException appEx = new AppException("Blah", new IllegalArgumentException());
    testSerializable(appEx);
  }
  
  // PRIVATE
  
  private  <T> void testSerializable(T aThing) throws FileNotFoundException, IOException, ClassNotFoundException  {
    OutputStream file = new FileOutputStream( "C:\\Temp\\test.ser" );
    OutputStream buffer = new BufferedOutputStream( file );
    ObjectOutput output = new ObjectOutputStream( buffer );
    try{
      output.writeObject(aThing);
    }
    finally{
      output.close();
    }

    InputStream inFile = new FileInputStream( "C:\\Temp\\test.ser" );
    InputStream inBuffer = new BufferedInputStream( inFile );
    ObjectInput input = new ObjectInputStream ( inBuffer );
    try{
      T recovered = (T)input.readObject();
    }
    finally{
      input.close();
    }
  }
}
