Source code: JObjectFormat.java
|
[ index | 123 lines | javadoc ]
|
package nl.west.aaa;
import java.io.*;
import java.util.*;
public class JObjectFormat
implements RecordFormat
{
/**
* Magic object is used to quoickly identify the stream.
* A message object may be of greater length.
*/
private static Object magicObject=new String("JObjectFormat:1234567");
/**
* Write out the Message to the OutputStream.
*/
private void writeMessage(Message msg,OutputStream out)
throws IOException
{
ObjectOutputStream os=new ObjectOutputStream(out);
os.writeObject(magicObject);
os.writeInt(msg.getMessageType());
os.writeObject(msg.getAttributes());
//os.writeObject(msg);
}
public byte[] encodeMessage(Message msg)
{
try
{
ByteArrayOutputStream out=new ByteArrayOutputStream();
writeMessage(msg,out);
return out.toByteArray();
}
catch (IOException e)
{
return null;
}
}
/**
* Read a Message from the InputStream.
* The stream should be tested as using the JObjectFormat
* record format with checkHeader().
* The read message is returned.
* If no message is found null is returned.
*/
public Message decodeMessage(InputStream in,Identifier from)
throws IOException
{
// first check for the magic object
boolean result=false;
ObjectInputStream os=null;
try
{
// mark current position in stream
in.mark(((String)magicObject).length()+20);
// make an objectstream
os=new ObjectInputStream(in);
// read magic object
Object o=os.readObject();
// test magic object
result=o.equals(magicObject);
}
catch (IOException e)
{
result=false; // not neccesary
}
catch (ClassNotFoundException e)
{
result=false; // not neccesary
}
if(!result)
{
// reset stream to orriginal position
// is in seporate try to execute even with exceptions
try
{
in.reset();
}
catch(IOException e)
{
// stream may be corrupt
}
return null;
}
// go on reading the message
Message msg=null;
try
{
// read the messagetype
int msgType=os.readInt();
Hashtable attrs=(Hashtable)os.readObject();
// read Message object
/* Object o=os.readObject();
if(!(o instanceof Message))
{
// throw some exception
System.err.println("JObjectFormat.decodeMessage(): object is not a message");
}
msg=(Message)o;*/
msg=new Message(msgType,attrs);
msg.sender=from;
}
catch (ClassNotFoundException e)
{
msg=null;
e.printStackTrace(System.err);
// throw some exception
}
return msg;
}
public Message decodeMessage(byte[] data,Identifier from)
{
// TODO: implement (put data in a stream and read it)
throw new RuntimeException("NOT YET IMPLEMENTED");
}
}
|