Source code: org/media/mn8/protocol/jabber/JabberDataBlockDispatcher.java
1 /*
2 * $COPYRIGHT$
3 * $Id: JabberDataBlockDispatcher.java,v 1.1 2002/04/09 16:47:46 crow Exp $
4 *
5 * Date Author Changes
6 * APR 08 2002 Szabo Csaba Created
7 */
8 package org.media.mn8.protocol.jabber;
9
10 import java.io.*;
11 import java.util.*;
12
13 /**
14 * The dispatcher for blocks that have arrived. Adds new blocks to the
15 * dispatch queue, and then dispatches waiting blocks in their own thread to
16 * avoid holding up the stream reader.
17 */
18 public class JabberDataBlockDispatcher extends Thread {
19 /**
20 * The recipient waiting on this stream
21 */
22 private JabberListener listener = null;
23
24 /**
25 * The list of messages waiting to be dispatched
26 */
27 private Vector waitingQueue = new Vector();
28
29 /**
30 * Flag to watch the dispatching loop
31 */
32 private boolean dispatcherActive;
33
34
35 /**
36 * Constructor to start the dispatcher in a thread.
37 */
38 public JabberDataBlockDispatcher() {
39 start();
40 }
41
42
43 /**
44 * Set the listener that we are dispatching to. Allows for switching
45 * of clients in mid stream.
46 *
47 * @param _listener The listener to dispatch to.
48 */
49 public void setJabberListener( JabberListener _listener ) {
50 listener = _listener;
51 }
52
53
54 /**
55 * Method to add a datablock to the dispatch queue
56 *
57 * @param datablock The block to add
58 */
59 public void broadcastJabberDataBlock( JabberDataBlock dataBlock ) {
60 waitingQueue.addElement( dataBlock );
61 }
62
63
64 /**
65 * The thread loop that handles dispatching any waiting datablocks
66 */
67 public void run() {
68 dispatcherActive = true;
69 while( dispatcherActive ) {
70 while( waitingQueue.size() == 0 ) {
71 try {
72 Thread.sleep( 100L );
73 } catch( InterruptedException e ) { }
74 }
75
76 JabberDataBlock dataBlock = (JabberDataBlock)waitingQueue.elementAt(0);
77 waitingQueue.removeElementAt( 0 );
78 if( listener != null ) listener.blockArrived( dataBlock );
79 }
80 }
81
82
83 /**
84 * Method to stop the dispatcher
85 */
86 public void halt() {
87 dispatcherActive = false;
88 }
89
90
91 /**
92 * Method to tell the listener the connection has been terminated
93 *
94 * @param exception The exception that caused the termination. This may be
95 * null for the situtations where the connection has terminated without an
96 * exception.
97 */
98 public void broadcastTerminatedConnection( Exception exception ) {
99 halt();
100 if( listener != null ) listener.connectionTerminated( exception );
101 }
102
103
104 /**
105 * Method to tell the listener the stream is ready for talking to.
106 */
107 public void broadcastBeginConversation( ) {
108 if( listener != null ) listener.beginConversation();
109 }
110 }