MoyaEventSender.java 2.5 KB
package fi.codecrew.moya.beans.moyamessage;

import java.util.Calendar;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.JMSDestinationDefinition;
import javax.jms.ObjectMessage;
import javax.jms.Topic;

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

import fi.codecrew.moya.beans.EventBeanLocal;
import fi.codecrew.moya.beans.LoggingBeanLocal;
import fi.codecrew.moya.beans.PermissionBeanLocal;
import fi.codecrew.moya.model.EventUser;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventMessage;
import fi.codecrew.moya.utilities.moyamessage.MoyaEventType;

@Stateless
@JMSDestinationDefinition(name = MoyaEventSender.MOYA_EVENT_SENDER_TOPIC,
		destinationName = MoyaEventSender.MOYA_EVENT_TOPIC_DESTINATION,
		description = "Events generated by moya to be logged or otherwise handler",
		interfaceName = "javax.jms.Topic"

)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
//@TransactionManagement(value = TransactionManagementType.CONTAINER)
public class MoyaEventSender implements LoggingBeanLocal {

	static final String MOYA_EVENT_TOPIC_DESTINATION = "moyaEventTopic";

	public static final String MOYA_EVENT_SENDER_TOPIC = "java:global/jms/moyaEventTopic";
	@EJB
	private EventBeanLocal eventbean;

	@EJB
	private PermissionBeanLocal permbean;

	@Inject
	JMSContext context;

	@Resource(mappedName = MOYA_EVENT_SENDER_TOPIC)
	Topic topic;

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

	@Override
	public void sendMessage(MoyaEventMessage moyaMessage) {
		ObjectMessage msg = context.createObjectMessage(moyaMessage);
		context.createProducer().send(topic, msg);
	}

	@Override
	public void sendMessage(MoyaEventType type, EventUser user, String message) {

		MoyaEventMessage msg = new MoyaEventMessage();
		msg.setEventtype(type);
		msg.setTime(Calendar.getInstance());
		msg.setEventUserId(user.getId());
		msg.setCurrentUserId(permbean.getCurrentUser().getUser().getId());
		msg.setEventId(eventbean.getCurrentEvent().getId());
		msg.setDescription(message);
		logger.info("Sending Moya message {} with description ", type, message);
		sendMessage(msg);
	}

	@Override
	public void sendMessage(MoyaEventType type, EventUser user, Object... message) {
		StringBuilder sb = new StringBuilder();
		for (Object m : message) {
			sb.append(m);
		}
		sendMessage(type, user, sb.toString());

	}

}