1 package transport.packet; 2 3 import java.io.*; 4 import java.net.InetAddress ; 5 import java.util.*; 6 7 import org.apache.commons.logging.Log; 8 import org.apache.commons.logging.LogFactory; 9 10 11 12 public class Packet implements Serializable, Cloneable 13 { 14 private static transient Log LOG = LogFactory.getLog(Packet.class); 15 16 private PacketTypeEnum type; 17 private long serial; 18 private long createDate = System.currentTimeMillis(); 19 protected Object payload; 20 private InetAddress ip; 21 private int port; 22 23 protected transient int channelID; 24 25 26 public Packet(PacketTypeEnum t, Object o) 27 { 28 type = t; 29 payload = o; 30 } 31 32 public void setChannelID(int id) 33 { 34 channelID = id; 35 } 36 37 public int getChannelID() 38 { 39 return channelID; 40 } 41 42 public PacketTypeEnum getType() 43 { 44 return type; 45 } 46 47 public long getSerial() 48 { 49 return serial; 50 } 51 52 53 public String toString() 54 { 55 StringBuffer buf = new StringBuffer (); 56 buf.append("type="); 57 buf.append(type); 58 buf.append("; serial="); 59 buf.append(Long.toString(serial)); 60 buf.append("; created="); 61 buf.append(new Date(createDate)); 62 63 return buf.toString(); 64 } 65 66 public void setPayload( Object o ) 67 { 68 payload = o; 69 } 70 71 public Object getPayload() 72 { 73 return payload; 74 } 75 76 public synchronized byte[] toBytes() 77 { 78 byte[] bytes; 79 try 80 { 81 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 82 ObjectOutputStream oos = new ObjectOutputStream( baos ); 83 oos.writeObject( this ); 84 oos.close(); 85 bytes = baos.toByteArray(); 86 } 87 catch(IOException e) 88 { 89 e.printStackTrace(); 90 bytes = new byte[0]; 93 } 94 return bytes; 95 } 96 97 public boolean isType(PacketTypeEnum t) 98 { 99 return t.equals(type); 100 } 101 102 public static Packet fromBytes( byte[] bytes ) 103 throws MalformedPacketException 104 105 { 106 Packet new_packet = null; 107 108 try 109 { 110 ByteArrayInputStream bais = new ByteArrayInputStream( bytes ); 111 ObjectInputStream ois = new ObjectInputStream( bais ); 112 new_packet = (Packet) ois.readObject(); 113 } 114 catch( ClassNotFoundException e ) 115 { 116 throw new MalformedPacketException(e.toString()); 117 } 118 catch( IOException e ) 119 { 120 throw new MalformedPacketException(e.toString()); 121 } 122 123 return new_packet; 124 } 125 126 129 public Calendar getCreateDate() 130 { 131 Calendar cal = Calendar.getInstance(); 132 cal.setTimeInMillis(createDate); 133 return cal; 134 } 135 136 139 public void setSerial(long serial) 140 { 141 this.serial = serial; 142 } 143 144 147 public void setType(PacketTypeEnum type) 148 { 149 this.type = type; 150 } 151 152 public void setIP(InetAddress ia) { ip = ia; } 153 public InetAddress getIP() { return ip; } 154 public void setPort(int p) { port = p; } 155 public int getPort() { return port; } 156 } 157 | Popular Tags |