
package it.mice.voila.runtime.runtime.jms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * A service that sends and receives JMS messages. 
 * 
 */
public class JMSMessageService 
{
	
	private JmsTemplate jmsTemplate;
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public String getDestination() {
		return destination;
	}

	public void setDestination(String destination) {
		this.destination = destination;
	}

	private String destination;

	/**
	 * Sends a message to a queue.
	 * 
	 * @param text Message text.
	 */
	public void sendMessage(final String text) {
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(text);
			}
		});
	}
	
	/**
	 * Receives a message from a queue.
	 * 
	 * @return Message text.
	 * @throws JMSException
	 */
	public String readMessage() {
		String message = null;
		
		Message msg = jmsTemplate.receive(destination);
		if(msg instanceof TextMessage) {
			try {
				message = ((TextMessage) msg).getText();
			} catch ( JMSException  e) {
				//TODO business ??? o wrap di una eccezione tipizzata per la coda.
				throw new RuntimeException(e);
			}
		}
		
		return message;
	}
}