/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 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: AuditSystemContextInterceptor.java 19722 2010-04-21 13:28:10Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.jndi.interceptors.impl.audit;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.management.MalformedObjectNameException;
import javax.management.Notification;
import javax.management.ObjectName;
import javax.management.modelmbean.ModelMBeanNotificationBroadcaster;

import org.ow2.carol.jndi.intercept.ContextInterceptor;
import org.ow2.carol.jndi.intercept.InterceptionContext;
import org.ow2.jonas.jndi.interceptors.impl.AbsContextInterceptor;
import org.ow2.util.auditreport.api.AuditorJMXObjectNames;
import org.ow2.util.auditreport.api.IAuditID;
import org.ow2.util.auditreport.api.ICurrentInvocationID;
import org.ow2.util.auditreport.impl.CurrentInvocationID;
import org.ow2.util.auditreport.impl.JNDIAuditReport;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Context interceptor for JNDI calls.
 * @author Mathieu ANCELIN
 */
public class AuditSystemContextInterceptor extends AbsContextInterceptor implements ContextInterceptor {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(AuditSystemContextInterceptor.class);

    /**
     * Notification sender.
     */
    private ModelMBeanNotificationBroadcaster broadcaster = null;

    /**
     * The number of the notification.
     */
    private long seqNumber = 0;

    /**
     * Default constructor.
     */
    public AuditSystemContextInterceptor() {
        super();
        setMethodsRegexp(".*");
    }

    /**
     * Intercept every JNDI call.
     * @param context the interception context with data
     * @return the wrapped result of the call.
     * @throws Exception if interception fails
     */
    public Object intercept(final InterceptionContext context) throws Exception {
        long requestStart = System.nanoTime();
        // Invoke the call in order to get the result
        Object obj = null;
        ICurrentInvocationID currentInvocationID = CurrentInvocationID.getInstance();
        IAuditID oldID = currentInvocationID.newInvocation();
        try {
            obj = context.proceed();
        } finally {
            long requestStop = System.nanoTime();

            // Do some stuff if we're interested in a given method
            Method method = context.getMethod();

            // React on all methods
            if (filterOnMethodName(method)) {

                Object[] parameters = context.getParameters();
                String param = "";
                String[] params = null;
                if (parameters != null && parameters.length > 0) {
                    param = parameters[0].toString();
                    int i = 0;
                    params = new String[parameters.length];
                    for (Object parameter : parameters) {
                        params[i++] = parameter.toString();
                    }
                }

                long totalGarbageCollections = 0;
                long garbageCollectionTime = 0;
                for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
                    long count = gc.getCollectionCount();
                    if (count >= 0) {
                        totalGarbageCollections += count;
                    }
                    long time = gc.getCollectionTime();
                    if (time >= 0) {
                        garbageCollectionTime += time;
                    }
                }

                JNDIAuditReport report = new JNDIAuditReport(System.currentTimeMillis(), context.getMethod().getName(), param,
                        params, Thread.currentThread(), requestStart, requestStop);
                report.setMethodStackTrace(cleanupStackTrace(Thread.currentThread().getStackTrace()));

                // Sets the current ID
                report.setKeyID(currentInvocationID.getAuditID().getID());

                // reset
                currentInvocationID.setAuditID(oldID);

                report.setSweepMarkTime(totalGarbageCollections);
                report.setScavengeTime(garbageCollectionTime);
                if (broadcaster == null) {
                    logger.error("No broadcaster available for JNDI Audit interceptor");
                } else if (report != null) {
                    broadcaster.sendNotification(new Notification("JNDI", broadcaster, getNextSeqNumber(), report.toString()));
                }
            }

        }
        // Let the Object unchanged
        return obj;
    }

    /**
     * Cleanup the stack trace elements to ave the right stack.
     * @param stackTrace the given stack
     * @return the cleanup stack
     */
    protected static StackTraceElement[] cleanupStackTrace(final StackTraceElement[] stackTrace) {
        List<StackTraceElement> cleanList = new ArrayList<StackTraceElement>();
        boolean initialContextFound = false;
        for (StackTraceElement stackElement : stackTrace) {
            String className = stackElement.getClassName();
            if (className != null) {
                // remove all the lines before the call to the initialContext class
                if (className.startsWith("javax.naming.InitialContext")) {
                    initialContextFound = true;
                }
                if (initialContextFound) {
                    cleanList.add(stackElement);
                }
            }
        }
        return cleanList.toArray(new StackTraceElement[cleanList.size()]);
    }
    /**
     * @param domain the domain name of the JMX Server.
     * @return a different objectname for this object.
     */
    @Override
    public ObjectName getObjectName(final String domain) {
        try {
            return new ObjectName(domain + AuditorJMXObjectNames.JNDIAUDITOR_TYPE_COMPONENT + ",name=JOnAS");
        } catch (MalformedObjectNameException e) {
            throw new IllegalStateException("Error while creating JNDI Audit ObjectName", e);
        } catch (NullPointerException e) {
            throw new IllegalStateException("Error while creating JNDI Audit ObjectName", e);

        }
    }

    /**
     * Sets the given broadcaster in order to send notification.
     * @param broadcaster the given object
     */
    public void setBroadcaster(final ModelMBeanNotificationBroadcaster broadcaster) {
        this.broadcaster = broadcaster;
    }

    /**
     * @return the next sequence number.
     */
    protected long getNextSeqNumber() {
        return seqNumber++;
    }
}
