1 24 25 package org.objectweb.tribe.messages; 26 27 import java.io.ByteArrayOutputStream ; 28 import java.io.IOException ; 29 import java.io.ObjectOutputStream ; 30 import java.io.Serializable ; 31 import java.util.ArrayList ; 32 import java.util.HashMap ; 33 34 import org.objectweb.tribe.channel.ReceiveBuffer; 35 import org.objectweb.tribe.exceptions.NoReceiverException; 36 37 46 public abstract class ChannelMessage implements Serializable 47 { 48 private Object key; private ArrayList chunks; 50 private transient byte[] messageInBytes = null; 51 52 57 public ChannelMessage(Object destinationKey) 58 { 59 chunks = new ArrayList (); 60 this.key = destinationKey; 61 } 62 63 69 public ChannelMessage(Object destinationKey, int numberOfChunks) 70 { 71 chunks = new ArrayList (numberOfChunks); 72 this.key = destinationKey; 73 } 74 75 80 public synchronized void addChunk(Serializable chunk) 81 { 82 messageInBytes = null; 83 chunks.add(chunk); 84 } 85 86 92 public ArrayList getChunks() 93 { 94 return chunks; 95 } 96 97 103 public synchronized Object removeChunk() 104 { 105 messageInBytes = null; 106 int size = chunks.size(); 107 if (size == 0) 108 return null; 109 else 110 return chunks.remove(size - 1); 111 } 112 113 120 public Object getDestinationKey() 121 { 122 return key; 123 } 124 125 133 public void deliverMessage(HashMap receiveBuffers) throws NoReceiverException 134 { 135 ArrayList buffers; 136 synchronized (receiveBuffers) 137 { 138 buffers = (ArrayList ) receiveBuffers.get(key); 140 } 141 if (buffers == null) 142 throw new NoReceiverException("No receive buffer to deliver message for " 143 + key); 144 145 synchronized (buffers) 148 { 149 int size = buffers.size(); 150 for (int i = 0; i < size; i++) 151 { 152 ReceiveBuffer buf = (ReceiveBuffer) buffers.get(i); 153 buf.addMessage(this); 154 } 155 } 156 } 157 158 166 public synchronized byte[] getByteArray() 167 { 168 if (messageInBytes == null) 169 { 170 try 171 { 172 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 173 new ObjectOutputStream (baos).writeObject(this); 174 messageInBytes = baos.toByteArray(); 175 } 176 catch (IOException e) 177 { 178 messageInBytes = null; 179 e.printStackTrace(); 180 } 181 } 182 return messageInBytes; 183 } 184 185 } | Popular Tags |