2008-03-19 22:14:38 +00:00
|
|
|
|
|
|
|
package net.sourceforge.tuned;
|
|
|
|
|
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.List;
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
|
|
import javax.swing.SwingUtilities;
|
|
|
|
|
|
|
|
|
|
|
|
public class MessageBus {
|
|
|
|
|
|
|
|
private static final MessageBus instance = new MessageBus();
|
|
|
|
|
|
|
|
|
|
|
|
public static MessageBus getDefault() {
|
|
|
|
return instance;
|
|
|
|
}
|
|
|
|
|
2008-07-30 22:37:01 +00:00
|
|
|
private final Map<String, List<MessageHandler>> handlers = new HashMap<String, List<MessageHandler>>();
|
2008-03-19 22:14:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
public synchronized void addMessageHandler(String topic, MessageHandler handler) {
|
2008-10-22 22:07:02 +00:00
|
|
|
if (handler == null)
|
|
|
|
return;
|
2008-07-30 22:37:01 +00:00
|
|
|
|
|
|
|
List<MessageHandler> list = handlers.get(topic.toLowerCase());
|
2008-03-19 22:14:38 +00:00
|
|
|
|
|
|
|
if (list == null) {
|
|
|
|
list = new ArrayList<MessageHandler>(3);
|
2008-07-30 22:37:01 +00:00
|
|
|
handlers.put(topic.toLowerCase(), list);
|
2008-03-19 22:14:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
list.add(handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public synchronized void removeMessageHandler(String topic, MessageHandler handler) {
|
2008-07-30 22:37:01 +00:00
|
|
|
List<MessageHandler> list = handlers.get(topic.toLowerCase());
|
2008-03-19 22:14:38 +00:00
|
|
|
|
|
|
|
if (list != null) {
|
|
|
|
list.remove(handler);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public synchronized MessageHandler[] getHandlers(String topic) {
|
2008-07-30 22:37:01 +00:00
|
|
|
List<MessageHandler> list = handlers.get(topic.toLowerCase());
|
2008-03-19 22:14:38 +00:00
|
|
|
|
|
|
|
if (list == null)
|
|
|
|
return new MessageHandler[0];
|
|
|
|
|
|
|
|
return list.toArray(new MessageHandler[0]);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2008-07-30 22:37:01 +00:00
|
|
|
public void publish(final String topic, final Object... messages) {
|
2008-10-22 22:07:02 +00:00
|
|
|
if (SwingUtilities.isEventDispatchThread()) {
|
|
|
|
publishDirect(topic, messages);
|
|
|
|
} else {
|
|
|
|
SwingUtilities.invokeLater(new Runnable() {
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
publishDirect(topic, messages);
|
2008-03-19 22:14:38 +00:00
|
|
|
}
|
2008-10-22 22:07:02 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private void publishDirect(String topic, Object... messages) {
|
|
|
|
for (MessageHandler handler : getHandlers(topic.toLowerCase())) {
|
|
|
|
handler.handle(topic.toLowerCase(), messages);
|
|
|
|
}
|
2008-03-19 22:14:38 +00:00
|
|
|
}
|
2008-10-10 19:20:37 +00:00
|
|
|
|
2008-03-19 22:14:38 +00:00
|
|
|
}
|