1 17 package org.apache.excalibur.event.impl; 18 19 import java.util.Collection ; 20 import java.util.Iterator ; 21 import java.util.LinkedList ; 22 23 import org.apache.excalibur.event.PreparedEnqueue; 24 import org.apache.excalibur.event.Sink; 25 import org.apache.excalibur.event.SinkException; 26 import org.apache.excalibur.event.SinkFullException; 27 28 42 public class MultiCastSink implements Sink 43 { 44 45 private final Collection m_sinks; 46 47 48 private final int m_size; 49 50 51 private final boolean m_single; 52 53 64 public MultiCastSink(Collection sinks) 65 { 66 this(sinks, false); 67 } 68 69 80 public MultiCastSink(Collection sinks, boolean single) 81 { 82 m_sinks = sinks; 83 m_size = -1; 84 m_single = single; 85 } 86 87 91 public int canAccept() 92 { 93 return 0; 94 } 95 96 99 public boolean isFull() 100 { 101 return false; 102 } 103 104 107 public int maxSize() 108 { 109 return 0; 110 } 111 112 115 public void enqueue(Object element) throws SinkException 116 { 117 final PreparedEnqueue prepared; 118 prepared = prepareEnqueue(new Object [] { element }); 119 prepared.commit(); 120 } 121 122 125 public void enqueue(Object [] elements) throws SinkException 126 { 127 final PreparedEnqueue prepared = prepareEnqueue(elements); 128 prepared.commit(); 129 } 130 131 134 public boolean tryEnqueue(Object element) 135 { 136 try 137 { 138 enqueue(element); 139 return true; 140 } 141 catch (SinkException e) 142 { 143 return false; 144 } 145 } 146 147 150 public PreparedEnqueue prepareEnqueue(Object [] elements) 151 throws SinkException 152 { 153 154 156 final DefaultPreparedEnqueue prepares = new DefaultPreparedEnqueue(); 157 int successful = 0; 158 159 final Iterator sinks = m_sinks.iterator(); 160 161 while (sinks.hasNext()) 163 { 164 final Sink sink = (Sink) sinks.next(); 165 166 try 167 { 168 prepares.addPreparedEnqueue(sink.prepareEnqueue(elements)); 169 } 170 catch (SinkFullException e) 171 { 172 continue; 173 } 174 175 if (m_single) 177 { 178 return prepares; 179 } 180 successful++; 181 break; 182 183 } 184 if (successful < m_sinks.size()) 185 { 186 prepares.abort(); 188 189 throw new SinkFullException("Could not deliver elements."); 190 } 191 192 return prepares; 193 } 194 195 198 public int size() 199 { 200 return m_size; 201 } 202 203 212 private static final class DefaultPreparedEnqueue 213 implements PreparedEnqueue 214 { 215 218 private final Collection m_preparedEnqueues = new LinkedList (); 219 220 224 public void abort() 225 { 226 final Iterator iter = m_preparedEnqueues.iterator(); 227 228 while (iter.hasNext()) 229 { 230 ((PreparedEnqueue) iter.next()).abort(); 231 } 232 } 233 234 237 public void commit() 238 { 239 final Iterator iter = m_preparedEnqueues.iterator(); 240 241 while (iter.hasNext()) 242 { 243 ((PreparedEnqueue) iter.next()).commit(); 244 } 245 } 246 247 256 public void addPreparedEnqueue(PreparedEnqueue preparedEnqueue) 257 { 258 m_preparedEnqueues.add(preparedEnqueue); 259 } 260 } } 262 | Popular Tags |