Listing 2: The Java Header class

package mgr;
import java.util.*;
import java.io.*;

class Header extends Object implements Codes
{
  int dataSize;
  int msgCode;
  int time;
  int timeout;
  int headerFlags;
  int errCodes;
  byte [] senderContext;
  byte [] crc;

public Header()  
{
  Date date  = new Date();
  time = (int) (date.getTime() /1000); //current time in secs
  senderContext = new byte [32];
  crc = new byte [2];
}//Header()

public Header(DataInputStream hdr) //reconstituting constructor
{
  try
  {
    dataSize = hdr.readInt();
    msgCode = hdr.readInt();
    ...//you get the idea
    for (int i =  0; i< 32; i++) senderContext[i] = hdr.readByte();
    crc = new byte [2];
    crc[0] = (byte) hdr.readUnsignedByte();
    crc[1] = (byte) hdr.readUnsignedByte();
  }//try
  catch (IOException exception) //stream end 
  {...}
}// Header(DataInputStream hdr) 
  
void serialize(DataOutputStream out)
{
  byte [] hdrBytes = toByteArray();
  try
  {
    out.write(hdrBytes, 0, hdrBytes.length); //copy bytes to stream
    setCrc();
    //copy crc bytes to stream overriding existing crc values
    hdrBytes[hdrBytes.length - 2] = crc[0];
    hdrBytes[hdrBytes.length - 1] = crc[1];
  }//try
  catch(IOException exception)
  {... }//catch
}//serialize()
  
//mutataors
  public void msgCode (int code) {msgCode = code;}
  public void timeout (int secs) { timeout = secs; }
  public int dataSize(int size)  { dataSize = size; }
...
//accessors
  public int msgCode () {return msgCode ;}
  public int timeout () { return timeout; }
  public int dataSize()  { dataSize; }
  ...
  char computeCrc() //char is unsigned
  {...}

  byte [] toByteArray()  //return binary representation of header
  {
    ByteArrayOutputStream outbuf = new ByteArrayOutputStream();
    DataOutputStream  out = new DataOutputStream(outbuf);
    try
    {
      out.writeInt(dataSize);
      out.writeInt(msgCode);
      ...
      for (int i = 0; i < 32; i++) out.writeByte(senderContext[i]);
      out.writeByte(crc[0]);  //make buffer size the same as 
                              //sizeof(header),ie,backward compatible
      out.writeByte(crc[1]);
    }//try
    catch(IOException exception)
    {
      return null;  //null buffer indicates failure
    }//catch
    return outbuf.toByteArray();
  }//toByteArray()

  void setCrc() 
  {...}
}//Header
//End of file