View Javadoc

1   package javabot;
2   
3   import java.util.Collection;
4   
5   import cz.cuni.amis.pogamut.base.communication.command.ICommandListener;
6   import cz.cuni.amis.pogamut.base.communication.messages.CommandMessage;
7   import cz.cuni.amis.pogamut.base.component.bus.IComponentBus;
8   import cz.cuni.amis.pogamut.base.component.bus.exception.ComponentNotRunningException;
9   import cz.cuni.amis.pogamut.base.component.bus.exception.ComponentPausedException;
10  import cz.cuni.amis.pogamut.base.utils.logging.LogCategory;
11  import cz.cuni.amis.pogamut.defcon.communication.messages.commands.DefConCommand;
12  import cz.cuni.amis.utils.ClassUtils;
13  import cz.cuni.amis.utils.listener.IListener;
14  import cz.cuni.amis.utils.listener.Listeners;
15  import cz.cuni.amis.utils.listener.ListenersMap;
16  
17  /**
18   * Executes a command and reports to all listeners to that command.
19   * SendCommand is called by PogamutJBotSupport periodically when batches are being sent.
20   * @author Radek 'Black_Hand' Pibil
21   *
22   */
23  public class ActExecutor {
24  	
25  
26  	private ListenersMap<Class> listeners = new ListenersMap<Class>();
27  	
28  	private LogCategory log;
29  	
30  	private IComponentBus eventBus;
31  	
32  	private static class CommandMessageListenerNotifier implements Listeners.ListenerNotifier<IListener> {
33  		
34  		private CommandMessage msg;
35  		
36  		public void setMessage(CommandMessage msg) {
37  			this.msg = msg;
38  		}
39  
40  		@Override
41  		public void notify(IListener listener) {
42  			listener.notify(msg);
43  		}
44  
45  		@Override
46  		public Object getEvent() {
47  			return msg;
48  		}
49  	}
50  	
51  	private CommandMessageListenerNotifier notifier = new CommandMessageListenerNotifier();	
52  		
53  	public void act(CommandMessage command)
54  			throws ComponentNotRunningException, ComponentPausedException {
55  
56  		if (command instanceof DefConCommand)
57  			PogamutJBotSupport.addCommand((DefConCommand)command);
58  	}
59  
60  	public void addCommandListener(Class commandClass, ICommandListener listener) {
61  		listeners.add(commandClass, listener);
62  	}
63  
64  	public boolean isCommandListening(Class commandClass,
65  			ICommandListener listener) {
66  		return listeners.isListening(commandClass, listener);		
67  	}
68  
69  	public void removeCommandListener(Class commandClass,
70  			ICommandListener listener) {
71  		listeners.remove(commandClass, listener);
72  	}
73  	
74  	public void sendCommand(DefConCommand command) {
75  		// PogamutJBotSupport.writeToConsole("Sending: " + command);
76  		notifier.setMessage(command);
77  		Collection<Class> commandClasses = ClassUtils.getSubclasses(command.getClass());
78  		for (Class cls : commandClasses) {
79  			listeners.notify(cls, notifier);
80  		}
81  		if (!(command instanceof DefConCommand))
82  			return;
83  		
84  		command.perform();	
85  	}
86  }