BotBean.java 2.69 KB
package fi.codecrew.moya.beans;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.jms.JMSException;
import javax.jms.Message;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fi.codecrew.moya.facade.EventFacade;
import fi.codecrew.moya.facade.EventUserFacade;
import fi.codecrew.moya.facade.UserFacade;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.model.LanEvent;
import fi.codecrew.moya.model.User;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventMessage;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;
import fi.iudex.utils.irc.IrcBot;

/**
 * Session Bean implementation class BotBean
 */
@Singleton
@LocalBean
@Lock(LockType.READ)
public class BotBean implements BotBeanLocal {

	private static final Logger logger = LoggerFactory.getLogger(BotBean.class);

	/**
	 * Default constructor.
	 */
	public BotBean() {
	}

	private IrcBot bot;

	@EJB
	private EventFacade eventfacade;
	@EJB
	private UserFacade userfacade;
	@EJB
	private EventUserFacade eventuserfacade;
	private final Set<MoyaEventType> ignoreTypes = ConcurrentHashMap.newKeySet();

	public void message(Message message) {

		try {
			MoyaEventMessage msg = message.getBody(MoyaEventMessage.class);

			// do not flood irc-channel, message only really needed ones
			if (msg.getEventtype() != null && getIgnoreTypes().contains(msg.getEventtype()))
				return;

			String event = "unknown event";
			if (msg.getEventId() != null) {
				LanEvent e = eventfacade.find(msg.getEventId());
				if (e != null)
					event = e.getName();
			}
			StringBuilder sb = new StringBuilder();
			sb.append(event).append(" ");
			sb.append(msg.getEventtype()).append(" ");

			if (msg.getCurrentUserId() != null) {
				User user = userfacade.find(msg.getCurrentUserId());
				if (user != null) {
					sb.append("user: ").append(user.getLogin()).append(" ");
				}
			}
			if (msg.getEventUserId() != null) {
				EventUser eu = eventuserfacade.find(msg.getEventUserId());
				if (eu != null && !eu.getUser().getId().equals(msg.getCurrentUserId())) {
					sb.append("for user: ").append(eu.getUser().getLogin()).append(": ");
				}
			}
			sb.append(msg.getDescription());

			bot.say(sb.toString());
		} catch (JMSException e) {
			logger.warn("Error sending message", e);
			bot.say("Error parsing message " + e.getMessage());
		}
	}

	@Override
	public Set<MoyaEventType> getIgnoreTypes() {
		return ignoreTypes;
	}

	public IrcBot getBot() {
		return bot;
	}

	public void setBot(IrcBot bot) {
		this.bot = bot;
	}

	@Override
	public void addBot(IrcBot bot) {
		setBot(bot);

	}

}