/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.jmx.internal.interceptor;

import org.ow2.jonas.jmx.Interceptor;

import javax.interceptor.InvocationContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Final interceptor which will call MBeanServer method
 * @author Mohammed Boukada
 */
public class MBeanServerDelegateInterceptor implements Interceptor {

    /**
     * MBeanServer
     */
    private Object mbs;

    /**
     * Construct interceptor
     * @param mbs MBeanServer
     */
    public MBeanServerDelegateInterceptor(Object mbs) {
        this.mbs = mbs;
    }

    /**
     * Invoke the method with the invocation context as parameter
     * @param invocationContext use to apply the interceptors sequence
     * @return the result of the invocation
     * @throws Exception if invocation fails
     */
    public Object invoke(InvocationContext invocationContext) throws Exception {
        try {
            Method method = invocationContext.getMethod();
            Object[] parameters = invocationContext.getParameters();
            if (parameters == null || parameters.length == 0){
                return method.invoke(mbs);
            }
            return method.invoke(mbs, parameters);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t instanceof Exception) {
                throw (Exception) t;
            }
            throw e;
        }
    }
}
