/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ee.mejb;

import java.io.IOException;
import java.rmi.RemoteException;

import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.j2ee.ListenerRegistration;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

/**
 * ListenerRegistration implementation.
 */
public class ListenerRegistrationImpl implements ListenerRegistration {
    private JMXServiceURL[] urls = null;

    transient private MBeanServerConnection connection = null;
    transient private JMXConnector connector = null;
        transient private String connectionId = null;

    /**
     * A ListenerRegistration object allows to ad/remove listeners to notifications emitted by
     * MBeans which are registred in a remote MBeanServer
     * @param urls the remote MBean server url(s) allowing to connect to this server
     */
    public ListenerRegistrationImpl(JMXServiceURL[] urls) {
        this.urls = urls;
    }

    /**
     * Add notification listener
     * @param arg0 identifies the emitter MBean
     * @param arg1 the listener to add
     * @param arg2 the associated filter
     * @param arg3 the associated handback object
     * @exception InstanceNotFoundException emitter MBean not registered in the MBeanServer
     * @exception RemoteException operation failed
     */
    public void addNotificationListener(ObjectName arg0, NotificationListener arg1, NotificationFilter arg2, Object arg3)
    throws InstanceNotFoundException, RemoteException {
        MBeanServerConnection conn = null;
        try {
            conn = getConnection();
        } catch (Exception e) {
            throw new RemoteException(e.getMessage());
        }
        if (conn != null) {
            try {
                conn.addNotificationListener(arg0, arg1, arg2, arg3);
            } catch (IOException e) {
                throw new RemoteException(e.toString());
            }
        }

    }
    /**
     * Remove notification listener
     * @param arg0 identifies the emitter MBean
     * @param arg1 the listener to remove
     * @exception InstanceNotFoundException emitter MBean not registered in the MBeanServer
     * @exception ListenerNotFoundException arg1 not registered as listener
     * @exception RemoteException operation failed
     */
    public void removeNotificationListener(ObjectName arg0, NotificationListener arg1)
    throws InstanceNotFoundException, ListenerNotFoundException, RemoteException {
        MBeanServerConnection conn = null;
        try {
            conn = getConnection();
        } catch (Exception e) {
            throw new RemoteException(e.getMessage());
        }

        if (conn != null) {
            try {
                conn.removeNotificationListener(arg0, arg1);
            } catch (IOException  e) {
                throw new RemoteException(e.toString());
            }
        }
    }

    /**
     * Use urls provided by the constructor to create a connector (client side) and establish
     * connection. The first urls allowing connection is used, the rest is ignored.
     * @throws Exception Could not establish connection to the remote MBeanServer
     */
    private void createConnection() throws Exception {
        for (int i = 0; i < urls.length; i++) {
            JMXServiceURL jmxServiceUrl = urls[i];
            connector = JMXConnectorFactory.newJMXConnector(jmxServiceUrl, null);
            try {
                connector.connect();
                connection = connector.getMBeanServerConnection();
                break;
            } catch (Exception e) {
                // The connection could not be established because a of a communication problem
                // (IOException) or for security reasons (java.lang.SecurityException)
                // Try to close connection
                connection = null;
                connector.close();
                connector = null;
                throw e;
            }
        }
    }
    /**
     * Get connection with the remote MBeanServer.
     * @return the established connection (we could test it and possibly recrete it is necessary...)
     * @throws Exception Could not establish connection to the remote MBeanServer
     */
    private MBeanServerConnection getConnection() throws Exception {
        if (connection == null) {
            createConnection();
        }
        return connection;
    }
}
