All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.wamblee.general.SerializableInvocationHandler Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2005-2010 the original author or authors.
 * 
 * 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.wamblee.general;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Serialiable invocation handler that delegate to a possibly non-serializable object.
 * The trick is to store the object in a static map with a unique id and use the id to 
 * retrieve the object instead of storing the object. 
 * 
 * @author Erik Brakkee
 *
 * @param 
 */
class SerializableInvocationHandler implements InvocationHandler,
    Serializable {

    /**
     * We store a map of unique ids of invocation handlers to thread local
     * storage of the service. In this way, serialiability of the generated
     * proxy is obtained (required by framweorks such as wicket). Also,
     * different factories will still be separate and never use the same
     * threadlocal storage.
     */
    private static Map STORAGE = new ConcurrentHashMap();

    private static AtomicInteger COUNTER = new AtomicInteger();

    private int id;
    private Class clazz;

    /**
     * Constructs the handler.
     * 
     * @param aSvc
     *            Thread local for the service.
     * @param aClass
     *            Service interface class.
     */
    public SerializableInvocationHandler(T aSvc, Class aClass) {
        id = COUNTER.incrementAndGet();
        clazz = aClass;
        STORAGE.put(id, aSvc);
    }

    @Override
    public Object invoke(Object aProxy, Method aMethod, Object[] aArgs)
        throws Throwable {

        T local = (T)STORAGE.get(id);
        try {
            return aMethod.invoke(local, aArgs);
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy