/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 France Telecom R&D
 * 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.jndi.interceptors.impl.datasource;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.ow2.jonas.jndi.checker.api.IResourceChecker;
import org.ow2.jonas.jndi.checker.api.IResourceCheckerInfo;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * Invocation handler that will monitor the calls to the stop() method.
 * @author Florent Benoit
 */
public abstract class ConnectionProxy implements InvocationHandler {

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

    /**
     * Close method.
     */
    private static final Method CLOSE_METHOD = ConnectionClassUtils.getCloseMethod();

    /**
     * Link to the wrapped connection.
     */
    private Connection delegate = null;

    private boolean forceClose = false;

    /**
     * Filtered caller stack trace.
     */
    private List<StackTraceElement> callerStackTrace;

    /**
     * Constructor of the handler of the proxy.
     * @param delegate the wrapped connection
     */
    public ConnectionProxy(final Connection delegate) {
        this.delegate = delegate;
        initCallerStackTrace();
    }

    public void setForceClose(boolean forceClose) {
        this.forceClose = forceClose;
    }

    public boolean isForceClose() {
        return forceClose;
    }

    protected Connection delegate() {
        return delegate;
    }

    private void initCallerStackTrace() {

        // Get the current stack trace
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

        // Remove some elements of the stack trace (like
        // java.lang.Thread.dumpThreads(Native Method),
        // java.lang.Thread.getStackTrace(Thread.java:1383), etc)
        callerStackTrace = new ArrayList<StackTraceElement>();
        boolean wrapperFound = false;
        for (StackTraceElement stackTraceElement : stackTraceElements) {
            // Not yet found, don't add
            if (wrapperFound) {
                callerStackTrace.add(stackTraceElement);
            }
            // Matching item, add the next stack elements
            if (DatasourceWrapper.class.getName().equals(stackTraceElement.getClassName())
                    && "getConnection".equals(stackTraceElement.getMethodName())) {
                wrapperFound = true;
            }
        }
    }

    /**
     * Intercept methods called on the connection object.
     * @param proxy the proxy instance that the method was invoked on
     * @param method the <code>Method</code> instance corresponding to the
     *        interface method invoked on the proxy instance.
     * @param args an array of objects containing the values of the arguments
     *        passed in the method invocation on the proxy instance, or
     *        <code>null</code> if interface method takes no arguments.
     * @return the value to return from the method invocation on the proxy
     *         instance.
     * @throws Throwable the exception to throw from the method invocation on
     *         the proxy instance.
     */
    public Object invoke(final Object proxy, final Method method, final Object[] args) throws SQLException, Throwable {

        // A close method is called, can remove this connection as an opened
        // connection
        if (CLOSE_METHOD.equals(method)) {
            unregisterConnection();
        }

        // finally call the method on the object
        try {
            return method.invoke(delegate, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    protected abstract void unregisterConnection();

    public abstract void registerConnection();

    protected void autoCloseOrWarn(IResourceCheckerInfo resourceCheckerInfo) {

        // Print that the connection will be automatically closed
        if (isForceClose()) {
            logger.warn("JDBC connection not closed by the caller, close has been forced by the server. " +
                        "Stack trace of the getConnection() call is ''{0}''. Additional info ''{1}''",
                        callerStackTrace.toString().replace(",", "\n"),
                        resourceCheckerInfo.getCallerInfo());
            try {
                delegate().close();
            } catch (SQLException e) {
                logger.error("Unable to force the close of the JDBC connection", e);
            }
        } else {
            // Connection leak but not closed automatically
            logger.warn("JDBC connection not closed by the caller. " +
                        "Stack trace of the getConnection() call is ''{0}''. " +
                        "Additional info ''{1}''",
                        callerStackTrace.toString().replace(",", "\n"),
                        resourceCheckerInfo.getCallerInfo());
        }
    }
}

/**
 * Helper class in order to cache close() method.
 */
final class ConnectionClassUtils {

    /**
     * Utility class.
     */
    private ConnectionClassUtils() {

    }

    /**
     * @return the close() method
     */
    public static Method getCloseMethod() {
        try {
            return Connection.class.getMethod("close");
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException("Cannot get close method on connection", e);
        }
    }

}
