// AlarmListenerBean.java
// Message Driven  bean

package org.objectweb.alarm.beans;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.jms.JMSException;

import org.objectweb.jonas.service.ServiceException;
import org.objectweb.jonas.service.ServiceManager;

/**
 *
 */
public class AlarmListenerBean  implements MessageDrivenBean, MessageListener {   

    private transient MessageDrivenContext mdbContext;
    private transient AlarmService als = null;

    
    // ------------------------------------------------------------------
    // MessageDrivenBean implementation
    // ------------------------------------------------------------------

    /** 
     * Default constructor
     *
     */
    public AlarmListenerBean() {
    }

    /** 
     * Set the associated context. The container call this method
     * after the instance creation. 
     * The enterprise Bean instance should store the reference to the context
     * object in an instance variable. 
     * This method is called with no transaction context.
     *
     * @param MessageDrivenContext A MessageDrivenContext interface for the instance.
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */

    public void setMessageDrivenContext(MessageDrivenContext ctx) {
	mdbContext = ctx;
    } 

    /**
     * A container invokes this method before it ends the life of the message-driven object. 
     * This happens when a container decides to terminate the message-driven object. 
     *
     * This method is called with no transaction context. 
     *
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void ejbRemove() {
    }

    /**
     * The Message driven  bean must define an ejbCreate methods with no args.
     * We can do here all operations that will be common to all messages,
     * i.e. asking JNDI for bean homes, ...
     */
    public void ejbCreate() {

	// Get a reference on the AlarmService.
	try {
	    als = (AlarmService) ServiceManager.getInstance().getService("alarm");
	} catch (ServiceException e) {
	    new ServiceException("AlarmListenerBean Cannot find AlarmService:"+e);
	}
    }

    /**
     *  onMessage method
     */
    public void onMessage(Message message) {

	int sev = 0;
	String from = null;
	String reason = null;

	// Decode the message (MapMessage)
	MapMessage msg = (MapMessage) message;
	try {
	    sev = msg.getInt("Severity");
	    from = msg.getString("From");
	    reason = msg.getString("Reason");
	} catch (JMSException e) {
	    System.err.println("AlarmListenerBean exception:"+e);
	}

	// Give all messages to the AlarmManager.
	als.alarm(sev, from, reason);
    }
}
