package uc; import java.io.*; public abstract class UCMsg { // short public static final int MSGTYPE_SIZE = 2; public static final short REQUESTFORORDERS = 0; public static final short TACTICALORDERS = 1; public static final short MISSIONRESULTS = 2; public static final short SLEEPTIME = 3; public static final short TEXT = 4; public static final short MAINFRAMETEXT = 5; static public UCMsg interpretByteArray( byte[] data ) throws IOException { DataInputStream dataIn = new DataInputStream( new ByteArrayInputStream( data ) ); short msgType = readMsgType( dataIn ); switch( msgType ) { case REQUESTFORORDERS: return new RequestForOrdersUCMsg( data ); case TACTICALORDERS: return new TacticalOrdersUCMsg( data ); case MISSIONRESULTS: return new MissionResultsUCMsg( data ); case SLEEPTIME: return new SleepTimeUCMsg( data ); case TEXT: return new TextUCMsg( data ); case MAINFRAMETEXT: return new MainFrameTextUCMsg( data ); default: return new UnknownUCMsg( msgType, data ); } } static public UCMsg receive( DataInputStream dataIn ) throws IOException { int length = dataIn.readInt(); byte[] data = new byte[ length ]; dataIn.readFully( data ); UCMsg msg = interpretByteArray( data ); return msg; } public void send( DataOutputStream dataOut ) throws IOException { if( data != null ) { dataOut.writeInt( data.length ); dataOut.write( data ); } else { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream tempOut = new DataOutputStream( byteOut ); writeMsgType( tempOut ); write( tempOut ); dataOut.writeInt( byteOut.size() ); byteOut.writeTo( dataOut ); data = byteOut.toByteArray(); } dataOut.flush(); } void pack() throws IOException { if( data != null ) return; ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream( byteOut ); writeMsgType( dataOut ); write( dataOut ); data = byteOut.toByteArray(); } void unpack() { if( data == null || unpacked ) return; try { DataInputStream dataIn = new DataInputStream( new ByteArrayInputStream( data, MSGTYPE_SIZE, data.length - MSGTYPE_SIZE ) ); read( dataIn ); unpacked = true; } catch( IOException e ) { good = false; } } static public short readMsgType( DataInputStream in ) throws IOException { return in.readShort(); } public void writeMsgType( DataOutputStream out ) throws IOException { out.writeShort( type ); } public int getType() { return type; } public byte[] getData() { return data; } public boolean isGood() { return good; } public boolean isUnpacked() { return unpacked; } abstract void read( DataInputStream dataIn ) throws IOException; abstract void write( DataOutputStream dataOut ) throws IOException; abstract public void open( UCMessageable processor ); boolean good = true; short type; byte[] data; boolean unpacked; }