/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/

package org.activemq.util;

import EDU.oswego.cs.dl.util.concurrent.Executor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * A proxy to some service which offers an asynchronous way to invoke methods which
 * are void and don't throw exceptions. Calling the method results in a command object
 * being added to a queue for later execution.
 *
 * @version $Revision: 1.1.1.1 $
 */
public class AsyncProxy implements InvocationHandler {

    private Object realObject;
    private Executor executor;
    private Log log;

    public static Object createProxy(Class interfaceType, Object realObject, Executor executor) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{interfaceType},
                new AsyncProxy(realObject, executor));
    }

    public AsyncProxy(Object realObject, Executor executor) {
        this(realObject, executor, LogFactory.getLog(AsyncProxy.class));
    }

    public AsyncProxy(Object realObject, Executor executor, Log log) {
        this.realObject = realObject;
        this.executor = executor;
        this.log = log;
    }

    public AsyncProxy(Executor executor, Log log) {
        this.executor = executor;
        this.log = log;
    }

    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
        if (method.getReturnType() == void.class) {
            executor.execute(new Runnable() {
                public void run() {
                    doAsyncMethodInvoke(method, args);
                }
            });
            return null;
        }
        else {
            return method.invoke(realObject, args);
        }
    }

    protected void doAsyncMethodInvoke(Method method, Object[] args) {
        try {
            method.invoke(realObject, args);
        }
        catch (Throwable e) {
            log.warn("Caught exception: " + e, e);
        }
    }
}
