Source code: ReplyHandler.java
|
[ index | 80 lines | javadoc ]
|
package nl.west.aaa;
import java.util.*;
import java.io.*;
public class ReplyHandler
implements MessageHandler
{
/**
* Messages awaiting a reply. All incoming messages
* are first checked if they are a reply to
* any of these messages.
*/
private Hashtable awaitingReply=new Hashtable();
/**
* Prepare this message for receiving a reply.
* This should be done before sending the message
* because the reply micht come in
* before it is waited upon.
*/
public void prepareForReply(Message msg)
{
//msg.foundReply=null;
awaitingReply.put(msg,null);
}
/**
* Wait for a reply to the message to come in.
* This method blocks until a reply is handled.
*/
public Message waitForReply(Message msg,long timeout)
{
synchronized (msg)
{
try
{
// only wait if no reply is in yet
if(awaitingReply.get(msg)==null)
msg.wait(timeout);
}
catch (InterruptedException e)
{
}
Message reply=(Message)awaitingReply.get(msg);
// remove it as waiting for a reply
awaitingReply.remove(msg);
// return it
return reply;
}
}
/**
* If the message is a reply to a registered
* waiter, the waiter is woken up and
* true is returned.
*/
public boolean handleMessage(Message msg,AAAUnit unit)
{
// check all waiting messages
Enumeration e=awaitingReply.keys();
while(e.hasMoreElements())
{
Message orr=(Message)e.nextElement();
if(msg.isReplyTo(orr))
{
synchronized (orr)
{
//orr.foundReply=msg;
//awaitingReply.remove(orr);
orr.notifyAll();
return true;
}
}
}
return false;
}
}
|