/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.mx.remoting.event;

import javax.management.*;
import java.io.Serializable;

/**
 * ClassQueryExp is a QueryExp implementation that allows you
 * to check the ObjectName on a query against one or more
 * class names to make sure that they are the instanceof one or more
 * classes.   <P>
 *
 * Example code:
 *
 * <CODE><pre>
 *   ClassQueryExp query=new ClassQueryExp(MyMBean.class);
 *   Set beans=mbeanserver.queryMBeans(new ObjectName("*:*"),query);
 * </pre></CODE>
 *
 * The query in the above example will only return MBean ObjectInstances that
 * are an instanceof <tt>MyMBean</tt> class.
 *
 *
 * @author <a href="jhaynie@vocalocity.net">Jeff Haynie</a>
 * @version $Revision: 1.1 $
 */
public class ClassQueryExp implements QueryExp, Serializable
{
    private static final long serialVersionUID = -4099952623687795850L;

    public static final int AND = 1;
    public static final int OR  = 2;

    String classes[];
    int operator;
    transient MBeanServer mBeanServer;

    /**
     * default will create using a AND operator
     *
     * @param cl
     */
    public ClassQueryExp (Class cl[])
    {
        this(cl,OR);
    }
    /**
     * default will create using a AND operator
     *
     * @param cl
     */
    public ClassQueryExp (Class cl)
    {
        this(new Class[]{cl},AND);
    }
    public ClassQueryExp (Class cl, int operator)
    {
        this(new Class[]{cl},operator);
    }
    public ClassQueryExp (Class cl[], int operator)
    {
        this.classes = new String[cl.length];
        for (int c=0;c<cl.length;c++)
        {
            this.classes[c]=cl[c].getName();
        }
        this.operator = operator;
    }
    public boolean apply(ObjectName objectName) throws BadStringOperationException, BadBinaryOpValueExpException, BadAttributeValueExpException, InvalidApplicationException
    {
        try
        {
            for (int c=0;c<classes.length;c++)
            {
                boolean value=mBeanServer.isInstanceOf(objectName,classes[c]);
                if (value && operator==OR)
                {
                    return true;
                }
                else if (!value && operator==AND)
                {
                    return false;
                }
            }
            return (operator==OR?false:true);
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    /**
     * called by MBeanServer prior to apply
     *
     * @param mBeanServer
     */
    public void setMBeanServer(MBeanServer mBeanServer)
    {
        this.mBeanServer=mBeanServer;
    }
}