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

de.tsl2.nano.plugin.DecorationProxy Maven / Gradle / Ivy

Go to download

TSL2 Framework Commons (Collections, Actions/Excecution, Readers, Xml, Print, Mail, FuzzyFinder, Proxies, Network-Structure)

There is a newer version: 2.5.1
Show newest version
package de.tsl2.nano.plugin;

import static de.tsl2.nano.plugin.Plugins.LOG;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import de.tsl2.nano.core.ManagedException;
import de.tsl2.nano.core.util.StringUtil;

/**
 * Invokes all classpath implementations of Plugin. see {@link Plugins}
 * @param  implementation of Plugin
 * @author Tom
 * @version $Revision$ 
 */
class DecorationProxy implements InvocationHandler {
    
    private List implementations;

    public DecorationProxy(Class interfaze) {
        implementations = Plugins.getImplementations(interfaze);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // if (implementations.isEmpty())
        //     return null; // --> only for performance (e.g. on logging)
        boolean decoratingChain = args.length == 1 && args[0] != null && method.getReturnType().isAssignableFrom(args[0].getClass());
        Object[] result = new Object[] {decoratingChain ? args[0] : null}; //workaround on non final result used in inner class
        implementations.stream().filter(h->h.isEnabled()).forEach(h->{
            try {
                LOG.debug("==> starting plugin " + h + " with: " + method);
                result[0] = decoratingChain ? method.invoke(h, result[0]) : method.invoke(h, args);
                LOG.debug("<== finished plugin " + h + " with: " + method);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                System.out.println("Error on: " + method + "(" + StringUtil.toString(decoratingChain ? result[0] : args, -1) + ")");
                ManagedException.forward(e);
            }
        });
        LOG.info(implementations.size() + " plugins done on: " + method.getName() + " [" + StringUtil.fixString(StringUtil.toString(args, 60), 60) + "]");
        return result[0];
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy