1 24 25 package org.objectweb.tribe.messages; 26 27 import java.io.ByteArrayInputStream ; 28 import java.io.ByteArrayOutputStream ; 29 import java.io.IOException ; 30 import java.io.ObjectInputStream ; 31 import java.io.ObjectOutputStream ; 32 import java.io.Serializable ; 33 import java.net.DatagramPacket ; 34 35 import org.objectweb.tribe.common.IpAddress; 36 37 43 public class DatagramMessage implements Serializable 44 { 45 private IpAddress sourceAddress; 46 private IpAddress destinationAddress; 47 private byte[] content = null; 48 49 55 public DatagramMessage(IpAddress sourceAddress, IpAddress destinationAddress) 56 { 57 this.sourceAddress = sourceAddress; 58 this.destinationAddress = destinationAddress; 59 } 60 61 66 public IpAddress getDestinationAddress() 67 { 68 return destinationAddress; 69 } 70 71 76 public IpAddress getSourceAddress() 77 { 78 return sourceAddress; 79 } 80 81 86 public byte[] getContent() 87 { 88 return content; 89 } 90 91 96 public void setContent(byte[] content) 97 { 98 this.content = content; 99 } 100 101 106 public int getContentSize() 107 { 108 if (content == null) 109 return 0; 110 else 111 return content.length; 112 } 113 114 119 public DatagramPacket getDatagramPacket() 120 { 121 if (content == null) 122 content = objectToBytes(this); 123 return new DatagramPacket (content, content.length, getDestinationAddress() 124 .getAddress(), getDestinationAddress().getPort()); 125 } 126 127 134 public static Object getObjectFromDatagram(DatagramPacket datagram) 135 { 136 try 137 { 138 ObjectInputStream in = new ObjectInputStream (new ByteArrayInputStream ( 139 datagram.getData())); 140 return in.readObject(); 141 } 142 catch (IOException e) 143 { 144 return null; 145 } 146 catch (ClassNotFoundException e) 147 { 148 return null; 149 } 150 } 151 152 158 public static byte[] objectToBytes(Serializable obj) 159 { 160 if (obj == null) 161 return null; 162 try 163 { 164 ByteArrayOutputStream byteStream = new ByteArrayOutputStream (); 165 new ObjectOutputStream (byteStream).writeObject(obj); 166 return byteStream.toByteArray(); 167 } 168 catch (IOException ex) 169 { 170 throw new IllegalArgumentException (ex.toString()); 171 } 172 } 173 174 } | Popular Tags |