
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.Session;
import org.apache.activemq.ActiveMQConnectionFactory;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DataListener implements Runnable, MessageListener{

    ActiveMQConnectionFactory connectionFactory;
    DBManager dbm;
    String name;
    MessageConsumer consumidor;

    DataListener(ActiveMQConnectionFactory connectionFactory, DBManager dbm, String name){
        this.connectionFactory = connectionFactory;
        this.dbm = dbm;
        this.name = new String(name);
    }

    public void run() {
        
        try {
            Connection conexion = connectionFactory.createConnection();
            conexion.start();
            Session sesion = conexion.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination cola = sesion.createQueue("DataQueue:"+name);
            consumidor = sesion.createConsumer(cola);
            consumidor.setMessageListener(this);
        } catch (JMSException ex) {
            System.out.println("Error al crear conexión: "+ex.getMessage());
        }
        
    }

    public void onMessage(Message msg) {
        try {
            MapMessage mm = (MapMessage) msg;
           
            String query = "INSERT INTO reactor(name,temperature,pressure) VALUES('" + mm.getString("Name") + "'," + mm.getInt("Temperature") + "," + mm.getFloat("Pressure") + ")";
            System.out.println(query);
            this.dbm.Query(query);
        } catch (JMSException ex) {
            System.out.println("Error al leer mensaje: "+ex.getMessage());
        }

    }

    


}
