
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 *
 * @author David Rodriguez A.
 */
public class ControlListener  implements Runnable, MessageListener {
    private ActiveMQConnectionFactory connectionFactory;
    private ActiveMQConnection connection;
    private Session session;
    private MessageConsumer consumer;
    private final Reactor reactor;

    public ControlListener(ActiveMQConnectionFactory connectionFactory, Reactor reactor){
       this.connectionFactory=connectionFactory;
       this.reactor=reactor;
    }

    public void run() {
        try {
            connection = (ActiveMQConnection) connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue("ControlQueue:"+this.reactor.getName());
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(this);
        } catch (JMSException ex) {
            Logger.getLogger(ControlListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void onMessage(Message msg) {
        try {
            MapMessage in_msg = (MapMessage) msg;
            System.out.println("("+this.reactor.getName()+") <<< MsgControl:" + in_msg.getString("CONTROL"));
            this.reactor.changeStatus();
        } catch (JMSException ex) {
            Logger.getLogger(Reactor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
