@Override
    @Nullable
    public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class<?>... actualInterfaces) throws IOException, ScriptCompilationException

package org.springframework.scripting.groovy;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.scripting.ScriptCompilationException;
import org.springframework.scripting.ScriptFactory;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

/**
 * {@link org.springframework.scripting.ScriptFactory} implementation
 * for a Groovy script.
 *
 *
Typically used in combination with a
 * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};
 * see the latter's javadoc for a configuration example.
 *
 *
Note: Spring 4.0 supports Groovy 1.8 and higher.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Rod Johnson
 * @since 2.0
 * @see groovy.lang.GroovyClassLoader
 * @see org.springframework.scripting.support.ScriptFactoryPostProcessor
 */
public class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {

    private final String scriptSourceLocator;

    @Nullable
    private GroovyObjectCustomizer groovyObjectCustomizer;

    @Nullable
    private CompilerConfiguration compilerConfiguration;

    @Nullable
    private GroovyClassLoader groovyClassLoader;

    @Nullable
    private Class<?> scriptClass;

    @Nullable
    private Class<?> scriptResultClass;

    @Nullable
    private CachedResultHolder cachedResult;

    private final Object scriptClassMonitor = new Object();

    private boolean wasModifiedForTypeCheck = false;

    /**
     * Create a new GroovyScriptFactory for the given script source.
     *
We don't need to specify script interfaces here, since
     * a Groovy script defines its Java interfaces itself.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     */
    public GroovyScriptFactory(String scriptSourceLocator) {
        Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty");
        this.scriptSourceLocator = scriptSourceLocator;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param groovyObjectCustomizer a customizer that can set a custom metaclass
     * or make other changes to the GroovyObject created by this factory
     * (may be {@code null})
     * @see GroovyObjectCustomizer#customize
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {
        this(scriptSourceLocator);
        this.groovyObjectCustomizer = groovyObjectCustomizer;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilerConfiguration a custom compiler configuration to be applied
     * to the GroovyClassLoader (may be {@code null})
     * @since 4.3.3
     * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {
        this(scriptSourceLocator);
        this.compilerConfiguration = compilerConfiguration;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can customize Groovy's compilation
     * process within the underlying GroovyClassLoader.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilationCustomizers one or more customizers to be applied to the
     * GroovyClassLoader compiler configuration
     * @since 4.3.3
     * @see CompilerConfiguration#addCompilationCustomizers
     * @see org.codehaus.groovy.control.customizers.ImportCustomizer
     */
    public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {
        this(scriptSourceLocator);
        if (!ObjectUtils.isEmpty(compilationCustomizers)) {
            this.compilerConfiguration = new CompilerConfiguration();
            this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        if (beanFactory instanceof ConfigurableListableBeanFactory) {
            ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);
        }
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {
            this.groovyClassLoader = (GroovyClassLoader) classLoader;
        } else {
            this.groovyClassLoader = buildGroovyClassLoader(classLoader);
        }
    }

    /**
     * Return the GroovyClassLoader used by this script factory.
     */
    public GroovyClassLoader getGroovyClassLoader() {
        synchronized (this.scriptClassMonitor) {
            if (this.groovyClassLoader == null) {
                this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());
            }
            return this.groovyClassLoader;
        }
    }

    /**
     * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.
     * @param classLoader the ClassLoader to build a GroovyClassLoader for
     * @since 4.3.3
     */
    protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {
        return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));
    }

    @Override
    public String getScriptSourceLocator() {
        return this.scriptSourceLocator;
    }

    /**
     * Groovy scripts determine their interfaces themselves,
     * hence we don't need to explicitly expose interfaces here.
     * @return {@code null} always
     */
    @Override
    @Nullable
    public Class<?>[] getScriptInterfaces() {
        return null;
    }

    /**
     * Groovy scripts do not need a config interface,
     * since they expose their setters as public methods.
     */
    @Override
    public boolean requiresConfigInterface() {
        return false;
    }

    /**
     * Loads and parses the Groovy script via the GroovyClassLoader.
     * @see groovy.lang.GroovyClassLoader
     */

{
        synchronized (this.scriptClassMonitor) {
            try {
                Class<?> scriptClassToExecute;
                this.wasModifiedForTypeCheck = false;
                if (this.cachedResult != null) {
                    Object result = this.cachedResult.object;
                    this.cachedResult = null;
                    return result;
                }
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        return result;
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                scriptClassToExecute = this.scriptClass;
                // Process re-execution outside of the synchronized block.
                return executeScript(scriptSource, scriptClassToExecute);
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    @Nullable
    public Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.wasModifiedForTypeCheck = true;
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        this.cachedResult = new CachedResultHolder(result);
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                return this.scriptResultClass;
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                this.cachedResult = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {
        synchronized (this.scriptClassMonitor) {
            return (scriptSource.isModified() || this.wasModifiedForTypeCheck);
        }
    }

    /**
     * Instantiate the given Groovy script class and run it if necessary.
     * @param scriptSource the source for the underlying script
     * @param scriptClass the Groovy script class
     * @return the result object (either an instance of the script class
     * or the result of running the script instance)
     * @throws ScriptCompilationException in case of instantiation failure
     */
    @Nullable
    protected Object executeScript(ScriptSource scriptSource, Class<?> scriptClass) throws ScriptCompilationException {
        try {
            GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();
            if (this.groovyObjectCustomizer != null) {
                // Allow metaclass and other customization.
                this.groovyObjectCustomizer.customize(goo);
            }
            if (goo instanceof Script) {
                // A Groovy script, probably creating an instance: let's execute it.
                return ((Script) goo).run();
            } else {
                // An instance of the scripted class: let's return it as-is.
                return goo;
            }
        } catch (NoSuchMethodException ex) {
            throw new ScriptCompilationException("No default constructor on Groovy script class: " + scriptClass.getName(), ex);
        } catch (InstantiationException ex) {
            throw new ScriptCompilationException(scriptSource, "Unable to instantiate Groovy script class: " + scriptClass.getName(), ex);
        } catch (IllegalAccessException ex) {
            throw new ScriptCompilationException(scriptSource, "Could not access Groovy script constructor: " + scriptClass.getName(), ex);
        } catch (InvocationTargetException ex) {
            throw new ScriptCompilationException("Failed to invoke Groovy script constructor: " + scriptClass.getName(), ex.getTargetException());
        }
    }

    @Override
    public String toString() {
        return "GroovyScriptFactory: script source locator [" + this.scriptSourceLocator + "]";
    }

    /**
     * Wrapper that holds a temporarily cached result object.
     */
    private static class CachedResultHolder {

        @Nullable
        public final Object object;

        public CachedResultHolder(@Nullable Object object) {
            this.object = object;
        }
    }
}


{
        return this.scriptSourceLocator;
    }

package org.springframework.scripting.groovy;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.scripting.ScriptCompilationException;
import org.springframework.scripting.ScriptFactory;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

/**
 * {@link org.springframework.scripting.ScriptFactory} implementation
 * for a Groovy script.
 *
 *
Typically used in combination with a
 * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};
 * see the latter's javadoc for a configuration example.
 *
 *
Note: Spring 4.0 supports Groovy 1.8 and higher.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Rod Johnson
 * @since 2.0
 * @see groovy.lang.GroovyClassLoader
 * @see org.springframework.scripting.support.ScriptFactoryPostProcessor
 */
public class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {

    private final String scriptSourceLocator;

    @Nullable
    private GroovyObjectCustomizer groovyObjectCustomizer;

    @Nullable
    private CompilerConfiguration compilerConfiguration;

    @Nullable
    private GroovyClassLoader groovyClassLoader;

    @Nullable
    private Class<?> scriptClass;

    @Nullable
    private Class<?> scriptResultClass;

    @Nullable
    private CachedResultHolder cachedResult;

    private final Object scriptClassMonitor = new Object();

    private boolean wasModifiedForTypeCheck = false;

    /**
     * Create a new GroovyScriptFactory for the given script source.
     *
We don't need to specify script interfaces here, since
     * a Groovy script defines its Java interfaces itself.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     */
    public GroovyScriptFactory(String scriptSourceLocator) {
        Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty");
        this.scriptSourceLocator = scriptSourceLocator;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param groovyObjectCustomizer a customizer that can set a custom metaclass
     * or make other changes to the GroovyObject created by this factory
     * (may be {@code null})
     * @see GroovyObjectCustomizer#customize
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {
        this(scriptSourceLocator);
        this.groovyObjectCustomizer = groovyObjectCustomizer;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilerConfiguration a custom compiler configuration to be applied
     * to the GroovyClassLoader (may be {@code null})
     * @since 4.3.3
     * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {
        this(scriptSourceLocator);
        this.compilerConfiguration = compilerConfiguration;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can customize Groovy's compilation
     * process within the underlying GroovyClassLoader.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilationCustomizers one or more customizers to be applied to the
     * GroovyClassLoader compiler configuration
     * @since 4.3.3
     * @see CompilerConfiguration#addCompilationCustomizers
     * @see org.codehaus.groovy.control.customizers.ImportCustomizer
     */
    public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {
        this(scriptSourceLocator);
        if (!ObjectUtils.isEmpty(compilationCustomizers)) {
            this.compilerConfiguration = new CompilerConfiguration();
            this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        if (beanFactory instanceof ConfigurableListableBeanFactory) {
            ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);
        }
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {
            this.groovyClassLoader = (GroovyClassLoader) classLoader;
        } else {
            this.groovyClassLoader = buildGroovyClassLoader(classLoader);
        }
    }

    /**
     * Return the GroovyClassLoader used by this script factory.
     */
    public GroovyClassLoader getGroovyClassLoader() {
        synchronized (this.scriptClassMonitor) {
            if (this.groovyClassLoader == null) {
                this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());
            }
            return this.groovyClassLoader;
        }
    }

    /**
     * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.
     * @param classLoader the ClassLoader to build a GroovyClassLoader for
     * @since 4.3.3
     */
    protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {
        return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));
    }

    @Override
    public String getScriptSourceLocator()

    /**
     * Groovy scripts determine their interfaces themselves,
     * hence we don't need to explicitly expose interfaces here.
     * @return {@code null} always
     */
    @Override
    @Nullable
    public Class<?>[] getScriptInterfaces() {
        return null;
    }

    /**
     * Groovy scripts do not need a config interface,
     * since they expose their setters as public methods.
     */
    @Override
    public boolean requiresConfigInterface() {
        return false;
    }

    /**
     * Loads and parses the Groovy script via the GroovyClassLoader.
     * @see groovy.lang.GroovyClassLoader
     */
    @Override
    @Nullable
    public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class<?>... actualInterfaces) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                Class<?> scriptClassToExecute;
                this.wasModifiedForTypeCheck = false;
                if (this.cachedResult != null) {
                    Object result = this.cachedResult.object;
                    this.cachedResult = null;
                    return result;
                }
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        return result;
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                scriptClassToExecute = this.scriptClass;
                // Process re-execution outside of the synchronized block.
                return executeScript(scriptSource, scriptClassToExecute);
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    @Nullable
    public Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.wasModifiedForTypeCheck = true;
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        this.cachedResult = new CachedResultHolder(result);
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                return this.scriptResultClass;
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                this.cachedResult = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {
        synchronized (this.scriptClassMonitor) {
            return (scriptSource.isModified() || this.wasModifiedForTypeCheck);
        }
    }

    /**
     * Instantiate the given Groovy script class and run it if necessary.
     * @param scriptSource the source for the underlying script
     * @param scriptClass the Groovy script class
     * @return the result object (either an instance of the script class
     * or the result of running the script instance)
     * @throws ScriptCompilationException in case of instantiation failure
     */
    @Nullable
    protected Object executeScript(ScriptSource scriptSource, Class<?> scriptClass) throws ScriptCompilationException {
        try {
            GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();
            if (this.groovyObjectCustomizer != null) {
                // Allow metaclass and other customization.
                this.groovyObjectCustomizer.customize(goo);
            }
            if (goo instanceof Script) {
                // A Groovy script, probably creating an instance: let's execute it.
                return ((Script) goo).run();
            } else {
                // An instance of the scripted class: let's return it as-is.
                return goo;
            }
        } catch (NoSuchMethodException ex) {
            throw new ScriptCompilationException("No default constructor on Groovy script class: " + scriptClass.getName(), ex);
        } catch (InstantiationException ex) {
            throw new ScriptCompilationException(scriptSource, "Unable to instantiate Groovy script class: " + scriptClass.getName(), ex);
        } catch (IllegalAccessException ex) {
            throw new ScriptCompilationException(scriptSource, "Could not access Groovy script constructor: " + scriptClass.getName(), ex);
        } catch (InvocationTargetException ex) {
            throw new ScriptCompilationException("Failed to invoke Groovy script constructor: " + scriptClass.getName(), ex.getTargetException());
        }
    }

    @Override
    public String toString() {
        return "GroovyScriptFactory: script source locator [" + this.scriptSourceLocator + "]";
    }

    /**
     * Wrapper that holds a temporarily cached result object.
     */
    private static class CachedResultHolder {

        @Nullable
        public final Object object;

        public CachedResultHolder(@Nullable Object object) {
            this.object = object;
        }
    }
}


package org.springframework.scripting.groovy;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.scripting.ScriptCompilationException;
import org.springframework.scripting.ScriptFactory;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

/**
 * {@link org.springframework.scripting.ScriptFactory} implementation
 * for a Groovy script.
 *
 *
Typically used in combination with a
 * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};
 * see the latter's javadoc for a configuration example.
 *
 *
Note: Spring 4.0 supports Groovy 1.8 and higher.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Rod Johnson
 * @since 2.0
 * @see groovy.lang.GroovyClassLoader
 * @see org.springframework.scripting.support.ScriptFactoryPostProcessor
 */
public class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {

    private final String scriptSourceLocator;

    @Nullable
    private GroovyObjectCustomizer groovyObjectCustomizer;

    @Nullable
    private CompilerConfiguration compilerConfiguration;

    @Nullable
    private GroovyClassLoader groovyClassLoader;

    @Nullable
    private Class<?> scriptClass;

    @Nullable
    private Class<?> scriptResultClass;

    @Nullable
    private CachedResultHolder cachedResult;

    private final Object scriptClassMonitor = new Object();

    private boolean wasModifiedForTypeCheck = false;

    /**
     * Create a new GroovyScriptFactory for the given script source.
     *
We don't need to specify script interfaces here, since
     * a Groovy script defines its Java interfaces itself.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     */
    public GroovyScriptFactory(String scriptSourceLocator) {
        Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty");
        this.scriptSourceLocator = scriptSourceLocator;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param groovyObjectCustomizer a customizer that can set a custom metaclass
     * or make other changes to the GroovyObject created by this factory
     * (may be {@code null})
     * @see GroovyObjectCustomizer#customize
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {
        this(scriptSourceLocator);
        this.groovyObjectCustomizer = groovyObjectCustomizer;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilerConfiguration a custom compiler configuration to be applied
     * to the GroovyClassLoader (may be {@code null})
     * @since 4.3.3
     * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {
        this(scriptSourceLocator);
        this.compilerConfiguration = compilerConfiguration;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can customize Groovy's compilation
     * process within the underlying GroovyClassLoader.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilationCustomizers one or more customizers to be applied to the
     * GroovyClassLoader compiler configuration
     * @since 4.3.3
     * @see CompilerConfiguration#addCompilationCustomizers
     * @see org.codehaus.groovy.control.customizers.ImportCustomizer
     */
    public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {
        this(scriptSourceLocator);
        if (!ObjectUtils.isEmpty(compilationCustomizers)) {
            this.compilerConfiguration = new CompilerConfiguration();
            this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        if (beanFactory instanceof ConfigurableListableBeanFactory) {
            ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);
        }
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {
            this.groovyClassLoader = (GroovyClassLoader) classLoader;
        } else {
            this.groovyClassLoader = buildGroovyClassLoader(classLoader);
        }
    }

    /**
     * Return the GroovyClassLoader used by this script factory.
     */
    public GroovyClassLoader getGroovyClassLoader() {
        synchronized (this.scriptClassMonitor) {
            if (this.groovyClassLoader == null) {
                this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());
            }
            return this.groovyClassLoader;
        }
    }

    /**
     * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.
     * @param classLoader the ClassLoader to build a GroovyClassLoader for
     * @since 4.3.3
     */
    protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {
        return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));
    }

    @Override
    public String getScriptSourceLocator() {
        return this.scriptSourceLocator;
    }

    /**
     * Groovy scripts determine their interfaces themselves,
     * hence we don't need to explicitly expose interfaces here.
     * @return {@code null} always
     */
    @Override
    @Nullable
    public Class<?>[] getScriptInterfaces() {
        ret

    }

    /**
     * Groovy scripts do not need a config interface,
     * since they expose their setters as public methods.
     */
    @Override
    public boolean requiresConfigInterface() {
        return false;
    }

    /**
     * Loads and parses the Groovy script via the GroovyClassLoader.
     * @see groovy.lang.GroovyClassLoader
     */
    @Override
    @Nullable
    public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class<?>... actualInterfaces) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                Class<?> scriptClassToExecute;
                this.wasModifiedForTypeCheck = false;
                if (this.cachedResult != null) {
                    Object result = this.cachedResult.object;
                    this.cachedResult = null;
                    return result;
                }
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        return result;
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                scriptClassToExecute = this.scriptClass;
                // Process re-execution outside of the synchronized block.
                return executeScript(scriptSource, scriptClassToExecute);
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    @Nullable
    public Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.wasModifiedForTypeCheck = true;
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        this.cachedResult = new CachedResultHolder(result);
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                return this.scriptResultClass;
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                this.cachedResult = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {
        synchronized (this.scriptClassMonitor) {
            return (scriptSource.isModified() || this.wasModifiedForTypeCheck);
        }
    }

    /**
     * Instantiate the given Groovy script class and run it if necessary.
     * @param scriptSource the source for the underlying script
     * @param scriptClass the Groovy script class
     * @return the result object (either an instance of the script class
     * or the result of running the script instance)
     * @throws ScriptCompilationException in case of instantiation failure
     */
    @Nullable
    protected Object executeScript(ScriptSource scriptSource, Class<?> scriptClass) throws ScriptCompilationException {
        try {
            GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();
            if (this.groovyObjectCustomizer != null) {
                // Allow metaclass and other customization.
                this.groovyObjectCustomizer.customize(goo);
            }
            if (goo instanceof Script) {
                // A Groovy script, probably creating an instance: let's execute it.
                return ((Script) goo).run();
            } else {
                // An instance of the scripted class: let's return it as-is.
                return goo;
            }
        } catch (NoSuchMethodException ex) {
            throw new ScriptCompilationException("No default constructor on Groovy script class: " + scriptClass.getName(), ex);
        } catch (InstantiationException ex) {
            throw new ScriptCompilationException(scriptSource, "Unable to instantiate Groovy script class: " + scriptClass.getName(), ex);
        } catch (IllegalAccessException ex) {
            throw new ScriptCompilationException(scriptSource, "Could not access Groovy script constructor: " + scriptClass.getName(), ex);
        } catch (InvocationTargetException ex) {
            throw new ScriptCompilationException("Failed to invoke Groovy script constructor: " + scriptClass.getName(), ex.getTargetException());
        }
    }

    @Override
    public String toString() {
        return "GroovyScriptFactory: script source locator [" + this.scriptSourceLocator + "]";
    }

    /**
     * Wrapper that holds a temporarily cached result object.
     */
    private static class CachedResultHolder {

        @Nullable
        public final Object object;

        public CachedResultHolder(@Nullable Object object) {
            this.object = object;
        }
    }
}


public GroovyClassLoader getGroovyClassLoader() {
        synchronized (this.scriptClassMonitor) {
            if (this.groovyClassLoader == null) {
                this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());
            }
            return this.groovyClassLoader;
        }
    }

package org.springframework.scripting.groovy;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.scripting.ScriptCompilationException;
import org.springframework.scripting.ScriptFactory;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

/**
 * {@link org.springframework.scripting.ScriptFactory} implementation
 * for a Groovy script.
 *
 *
Typically used in combination with a
 * {@link org.springframework.scripting.support.ScriptFactoryPostProcessor};
 * see the latter's javadoc for a configuration example.
 *
 *
Note: Spring 4.0 supports Groovy 1.8 and higher.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @author Rod Johnson
 * @since 2.0
 * @see groovy.lang.GroovyClassLoader
 * @see org.springframework.scripting.support.ScriptFactoryPostProcessor
 */
public class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, BeanClassLoaderAware {

    private final String scriptSourceLocator;

    @Nullable
    private GroovyObjectCustomizer groovyObjectCustomizer;

    @Nullable
    private CompilerConfiguration compilerConfiguration;

    @Nullable
    private GroovyClassLoader groovyClassLoader;

    @Nullable
    private Class<?> scriptClass;

    @Nullable
    private Class<?> scriptResultClass;

    @Nullable
    private CachedResultHolder cachedResult;

    private final Object scriptClassMonitor = new Object();

    private boolean wasModifiedForTypeCheck = false;

    /**
     * Create a new GroovyScriptFactory for the given script source.
     *
We don't need to specify script interfaces here, since
     * a Groovy script defines its Java interfaces itself.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     */
    public GroovyScriptFactory(String scriptSourceLocator) {
        Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty");
        this.scriptSourceLocator = scriptSourceLocator;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param groovyObjectCustomizer a customizer that can set a custom metaclass
     * or make other changes to the GroovyObject created by this factory
     * (may be {@code null})
     * @see GroovyObjectCustomizer#customize
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable GroovyObjectCustomizer groovyObjectCustomizer) {
        this(scriptSourceLocator);
        this.groovyObjectCustomizer = groovyObjectCustomizer;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can create a custom MetaClass
     * to supply missing methods and otherwise change the behavior of the object.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilerConfiguration a custom compiler configuration to be applied
     * to the GroovyClassLoader (may be {@code null})
     * @since 4.3.3
     * @see GroovyClassLoader#GroovyClassLoader(ClassLoader, CompilerConfiguration)
     */
    public GroovyScriptFactory(String scriptSourceLocator, @Nullable CompilerConfiguration compilerConfiguration) {
        this(scriptSourceLocator);
        this.compilerConfiguration = compilerConfiguration;
    }

    /**
     * Create a new GroovyScriptFactory for the given script source,
     * specifying a strategy interface that can customize Groovy's compilation
     * process within the underlying GroovyClassLoader.
     * @param scriptSourceLocator a locator that points to the source of the script.
     * Interpreted by the post-processor that actually creates the script.
     * @param compilationCustomizers one or more customizers to be applied to the
     * GroovyClassLoader compiler configuration
     * @since 4.3.3
     * @see CompilerConfiguration#addCompilationCustomizers
     * @see org.codehaus.groovy.control.customizers.ImportCustomizer
     */
    public GroovyScriptFactory(String scriptSourceLocator, CompilationCustomizer... compilationCustomizers) {
        this(scriptSourceLocator);
        if (!ObjectUtils.isEmpty(compilationCustomizers)) {
            this.compilerConfiguration = new CompilerConfiguration();
            this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers);
        }
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        if (beanFactory instanceof ConfigurableListableBeanFactory) {
            ((ConfigurableListableBeanFactory) beanFactory).ignoreDependencyType(MetaClass.class);
        }
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        if (classLoader instanceof GroovyClassLoader && (this.compilerConfiguration == null || ((GroovyClassLoader) classLoader).hasCompatibleConfiguration(this.compilerConfiguration))) {
            this.groovyClassLoader = (GroovyClassLoader) classLoader;
        } else {
            this.groovyClassLoader = buildGroovyClassLoader(classLoader);
        }
    }

    /**
     * Return the GroovyClassLoader used by this script factory.
     */

    /**
     * Build a {@link GroovyClassLoader} for the given {@code ClassLoader}.
     * @param classLoader the ClassLoader to build a GroovyClassLoader for
     * @since 4.3.3
     */
    protected GroovyClassLoader buildGroovyClassLoader(@Nullable ClassLoader classLoader) {
        return (this.compilerConfiguration != null ? new GroovyClassLoader(classLoader, this.compilerConfiguration) : new GroovyClassLoader(classLoader));
    }

    @Override
    public String getScriptSourceLocator() {
        return this.scriptSourceLocator;
    }

    /**
     * Groovy scripts determine their interfaces themselves,
     * hence we don't need to explicitly expose interfaces here.
     * @return {@code null} always
     */
    @Override
    @Nullable
    public Class<?>[] getScriptInterfaces() {
        return null;
    }

    /**
     * Groovy scripts do not need a config interface,
     * since they expose their setters as public methods.
     */
    @Override
    public boolean requiresConfigInterface() {
        return false;
    }

    /**
     * Loads and parses the Groovy script via the GroovyClassLoader.
     * @see groovy.lang.GroovyClassLoader
     */
    @Override
    @Nullable
    public Object getScriptedObject(ScriptSource scriptSource, @Nullable Class<?>... actualInterfaces) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                Class<?> scriptClassToExecute;
                this.wasModifiedForTypeCheck = false;
                if (this.cachedResult != null) {
                    Object result = this.cachedResult.object;
                    this.cachedResult = null;
                    return result;
                }
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        return result;
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                scriptClassToExecute = this.scriptClass;
                // Process re-execution outside of the synchronized block.
                return executeScript(scriptSource, scriptClassToExecute);
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    @Nullable
    public Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException {
        synchronized (this.scriptClassMonitor) {
            try {
                if (this.scriptClass == null || scriptSource.isModified()) {
                    // New script content...
                    this.wasModifiedForTypeCheck = true;
                    this.scriptClass = getGroovyClassLoader().parseClass(scriptSource.getScriptAsString(), scriptSource.suggestedClassName());
                    if (Script.class.isAssignableFrom(this.scriptClass)) {
                        // A Groovy script, probably creating an instance: let's execute it.
                        Object result = executeScript(scriptSource, this.scriptClass);
                        this.scriptResultClass = (result != null ? result.getClass() : null);
                        this.cachedResult = new CachedResultHolder(result);
                    } else {
                        this.scriptResultClass = this.scriptClass;
                    }
                }
                return this.scriptResultClass;
            } catch (CompilationFailedException ex) {
                this.scriptClass = null;
                this.scriptResultClass = null;
                this.cachedResult = null;
                throw new ScriptCompilationException(scriptSource, ex);
            }
        }
    }

    @Override
    public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) {
        synchronized (this.scriptClassMonitor) {
            return (scriptSource.isModified() || this.wasModifiedForTypeCheck);
        }
    }

    /**
     * Instantiate the given Groovy script class and run it if necessary.
     * @param scriptSource the source for the underlying script
     * @param scriptClass the Groovy script class
     * @return the result object (either an instance of the script class
     * or the result of running the script instance)
     * @throws ScriptCompilationException in case of instantiation failure
     */
    @Nullable
    protected Object executeScript(ScriptSource scriptSource, Class<?> scriptClass) throws ScriptCompilationException {
        try {
            GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance();
            if (this.groovyObjectCustomizer != null) {
                // Allow metaclass and other customization.
                this.groovyObjectCustomizer.customize(goo);
            }
            if (goo instanceof Script) {
                // A Groovy script, probably creating an instance: let's execute it.
                return ((Script) goo).run();
            } else {
                // An instance of the scripted class: let's return it as-is.
                return goo;
            }
        } catch (NoSuchMethodException ex) {
            throw new ScriptCompilationException("No default constructor on Groovy script class: " + scriptClass.getName(), ex);
        } catch (InstantiationException ex) {
            throw new ScriptCompilationException(scriptSource, "Unable to instantiate Groovy script class: " + scriptClass.getName(), ex);
        } catch (IllegalAccessException ex) {
            throw new ScriptCompilationException(scriptSource, "Could not access Groovy script constructor: " + scriptClass.getName(), ex);
        } catch (InvocationTargetException ex) {
            throw new ScriptCompilationException("Failed to invoke Groovy script constructor: " + scriptClass.getName(), ex.getTargetException());
        }
    }

    @Override
    public String toString() {
        return "GroovyScriptFactory: script source locator [" + this.scriptSourceLocator + "]";
    }

    /**
     * Wrapper that holds a temporarily cached result object.
     */
    private static class CachedResultHolder {

        @Nullable
        public final Object object;

        public CachedResultHolder(@Nullable Object object) {
            this.object = object;
        }
    }
}


package org.jsweet.transpiler.model.support;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.jsweet.transpiler.model.ImportElement;
import org.jsweet.transpiler.util.Util;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;

/**
 * See {@link ImportElement}.
 *
 * @author Renaud Pawlak
 * @author Louis Grignon
 */
public class ImportElementSupport extends ExtendedElementSupport<ImportTree> implements ImportElement {

    public ImportElementSupport(ImportTree tree) {
        super(tree);
    }

{
        return getTree().isStatic();
    }

    @Override
    public TypeElement getImportedType() {
        Tree importedIdentifier = getTree().getQualifiedIdentifier();
        Element importedElement = Util.getElement(importedIdentifier);
        if (getTree().isStatic() || importedElement == null || importedElement.asType() == null) {
            return null;
        }
        return (TypeElement) importedElement;
    }

    @Override
    public boolean isWildcard() {
        return getTree().toString().endsWith("*");
    }
}


{
        return getTree().isStatic();
    }

package org.jsweet.transpiler.model.support;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.jsweet.transpiler.model.ImportElement;
import org.jsweet.transpiler.util.Util;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;

/**
 * See {@link ImportElement}.
 *
 * @author Renaud Pawlak
 * @author Louis Grignon
 */
public class ImportElementSupport extends ExtendedElementSupport<ImportTree> implements ImportElement {

    public ImportElementSupport(ImportTree tree) {
        super(tree);
    }

    @Override
    public boolean isStatic()

    @Override
    public TypeElement getImportedType() {
        Tree importedIdentifier = getTree().getQualifiedIdentifier();
        Element importedElement = Util.getElement(importedIdentifier);
        if (getTree().isStatic() || importedElement == null || importedElement.asType() == null) {
            return null;
        }
        return (TypeElement) importedElement;
    }

    @Override
    public boolean isWildcard() {
        return getTree().toString().endsWith("*");
    }
}


package org.jsweet.transpiler.model.support;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import org.jsweet.transpiler.model.ImportElement;
import org.jsweet.transpiler.util.Util;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.Tree;

/**
 * See {@link ImportElement}.
 *
 * @author Renaud Pawlak
 * @author Louis Grignon
 */
public class ImportElementSupport extends ExtendedElementSupport<ImportTree> implements ImportElement {

    public ImportElementSupport(ImportTree tree) {
        super(tree);
    }

    @Override
    public boolean isStatic() {
        return getTree().isStatic();
    }

    @Override
    public TypeElement getImportedType() {
        Tree importedIdentifier = getTree().getQualifiedIdentifier();
        Element importedElement = Util.getElement(importedIdentifier);
        if (getTree().isStatic() || importedElement == null || importedElement.asType() == null) {
            return null;
        }
        return (TypeElement) importedE

    }

    @Override
    public boolean isWildcard() {
        return getTree().toString().endsWith("*");
    }
}


package com.sun.jna;

import com.sun.jna.internal.ReflectionUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Derive from this interface for all native library definitions.
 *
 * Define an instance of your library like this:
 *

 * MyNativeLibrary INSTANCE = (MyNativeLibrary)
 *     Native.load("mylib", MyNativeLibrary.class);
 *

 *

 * By convention, method names are identical to the native names, although you
 * can map java names to different native names by providing a
 * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}
 * in the options map passed to the
 * {@link Native#load(String, Class, Map)} call.
 *

 * Although the names for structures and structure fields may be chosen
 * arbitrarily, they should correspond as closely as possible to the native
 * definitions.  The same is true for parameter names.
 *

 * This interface supports multiple, concurrent invocations of any library
 * methods on the Java side.  Check your library documentation for its
 * multi-threading requirements on the native side.  If a library is not safe
 * for simultaneous multi-threaded access, consider using
 * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded
 * access to the native code.
 *

 * Optional fields

 * Interface options will be automatically propagated to structures defined
 * within the library provided a call to
 * {@link Native#load(String,Class,Map)} is made prior to instantiating
 * any of those structures.  One common way of ensuring this is to declare
 * an INSTANCE field in the interface which holds the
 * load result.
 *

 * OPTIONS (an instance of {@link Map}),
 * TYPE_MAPPER (an instance of {@link TypeMapper}),
 * STRUCTURE_ALIGNMENT (one of the alignment types defined in
 * {@link Structure}), and STRING_ENCODING (a {@link String}) may also
 * be defined.  If no instance of the interface has been instantiated, these
 * fields will be used to determine customization settings for structures and
 * methods defined within the interface.
 *

 *
 * @author  Todd Fast, example@nnthink.com
 * @author  Timothy Wall, example@nnthink.com
 */
public interface Library {

    /**
     * Option key for a {@link TypeMapper} for the library.
     */
    String OPTION_TYPE_MAPPER = "type-mapper";

    /**
     * Option key for a {@link FunctionMapper} for the library.
     */
    String OPTION_FUNCTION_MAPPER = "function-mapper";

    /**
     * Option key for an {@link InvocationMapper} for the library.
     */
    String OPTION_INVOCATION_MAPPER = "invocation-mapper";

    /**
     * Option key for structure alignment type ({@link Integer}), which should
     * be one of the predefined alignment types in {@link Structure}.
     */
    String OPTION_STRUCTURE_ALIGNMENT = "structure-alignment";

    /**
     *
Option key for per-library String encoding.  This affects conversions
     * between Java unicode and native (const char*) strings (as
     * arguments or Structure fields).
     *

     * Defaults to {@link Native#getDefaultStringEncoding()}.
     */
    String OPTION_STRING_ENCODING = "string-encoding";

    /**
     * Option key for a boolean flag to allow any Java class instance as a
     *        parameter.  If no type mapper is found, the object is passed as a
     *        pointer.
     *        NOTE: This is for use with raw JNI interactions via the
     *        JNIEnv data structure.
     */
    String OPTION_ALLOW_OBJECTS = "allow-objects";

    /**
     * Calling convention for the entire library.
     */
    String OPTION_CALLING_CONVENTION = "calling-convention";

    /**
     * Flags to use when opening the native library (see {@link Native#open(String,int)})
     */
    String OPTION_OPEN_FLAGS = "open-flags";

    /**
     *
Class loader to use when searching for native libraries on the
     * resource path (classpath).  If not provided the current thread's
     * context class loader is used.

     * If extracted from the resource path (i.e. bundled in a jar file), the
     * loaded library's lifespan will mirror that of the class loader, which
     * means you can use the same library in isolated contexts without
     * conflict.
     */
    String OPTION_CLASSLOADER = "classloader";

    static class Handler implements InvocationHandler {

        static final Method OBJECT_TOSTRING;

        static final Method OBJECT_HASHCODE;

        static final Method OBJECT_EQUALS;

        static {
            try {
                OBJECT_TOSTRING = Object.class.getMethod("toString");
                OBJECT_HASHCODE = Object.class.getMethod("hashCode");
                OBJECT_EQUALS = Object.class.getMethod("equals", Object.class);
            } catch (Exception e) {
                throw new Error("Error retrieving Object.toString() method");
            }
        }

        /**
         * FunctionInfo has to be immutable to to make the object visible
         * to other threads fully initialized. This is a prerequisite for
         * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}
         */
        private static final class FunctionInfo {

            final InvocationHandler handler;

            final Function function;

            final boolean isVarArgs;

            final Object methodHandle;

            final Map<String, ?> options;

            final Class<?>[] parameterTypes;

            FunctionInfo(Object mh) {
                this.handler = null;
                this.function = null;
                this.isVarArgs = false;
                this.options = null;
                this.parameterTypes = null;
                this.methodHandle = mh;
            }

            FunctionInfo(InvocationHandler handler, Function function, Class<?>[] parameterTypes, boolean isVarArgs, Map<String, ?> options) {
                this.handler = handler;
                this.function = function;
                this.isVarArgs = isVarArgs;
                this.options = options;
                this.parameterTypes = parameterTypes;
                this.methodHandle = null;
            }
        }

        private final NativeLibrary nativeLibrary;

        private final Class<?> interfaceClass;

        // Library invocation options
        private final Map<String, Object> options;

        private final InvocationMapper invocationMapper;

        private final Map<Method, FunctionInfo> functions = new WeakHashMap<Method, FunctionInfo>();

        public Handler(String libname, Class<?> interfaceClass, Map<String, ?> options) {
            if (libname != null && "".equals(libname.trim())) {
                throw new IllegalArgumentException("Invalid library name \"" + libname + "\"");
            }
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(libname + " does not implement an interface: " + interfaceClass.getName());
            }
            this.interfaceClass = interfaceClass;
            this.options = new HashMap<String, Object>(options);
            int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;
            if (this.options.get(OPTION_CALLING_CONVENTION) == null) {
                this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));
            }
            if (this.options.get(OPTION_CLASSLOADER) == null) {
                this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());
            }
            this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);
            invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);
        }

{
            return nativeLibrary;
        }

        public String getLibraryName() {
            return nativeLibrary.getName();
        }

        public Class<?> getInterfaceClass() {
            return interfaceClass;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {
            // Intercept Object methods
            if (OBJECT_TOSTRING.equals(method)) {
                return "Proxy interface to " + nativeLibrary;
            } else if (OBJECT_HASHCODE.equals(method)) {
                return Integer.valueOf(hashCode());
            } else if (OBJECT_EQUALS.equals(method)) {
                Object o = inArgs[0];
                if (o != null && Proxy.isProxyClass(o.getClass())) {
                    return Function.valueOf(Proxy.getInvocationHandler(o) == this);
                }
                return Boolean.FALSE;
            }
            // Using the double-checked locking pattern to speed up function calls
            FunctionInfo f = functions.get(method);
            if (f == null) {
                synchronized (functions) {
                    f = functions.get(method);
                    if (f == null) {
                        boolean isDefault = ReflectionUtils.isDefault(method);
                        if (!isDefault) {
                            boolean isVarArgs = Function.isVarArgs(method);
                            InvocationHandler handler = null;
                            if (invocationMapper != null) {
                                handler = invocationMapper.getInvocationHandler(nativeLibrary, method);
                            }
                            Function function = null;
                            Class<?>[] parameterTypes = null;
                            Map<String, Object> options = null;
                            if (handler == null) {
                                // Find the function to invoke
                                function = nativeLibrary.getFunction(method.getName(), method);
                                parameterTypes = method.getParameterTypes();
                                options = new HashMap<String, Object>(this.options);
                                options.put(Function.OPTION_INVOKING_METHOD, method);
                            }
                            f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);
                        } else {
                            f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));
                        }
                        functions.put(method, f);
                    }
                }
            }
            if (f.methodHandle != null) {
                return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);
            } else {
                if (f.isVarArgs) {
                    inArgs = Function.concatenateVarArgs(inArgs);
                }
                if (f.handler != null) {
                    return f.handler.invoke(proxy, method, inArgs);
                }
                return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);
            }
        }
    }
}


{
            return nativeLibrary.getName();
        }

package com.sun.jna;

import com.sun.jna.internal.ReflectionUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Derive from this interface for all native library definitions.
 *
 * Define an instance of your library like this:
 *

 * MyNativeLibrary INSTANCE = (MyNativeLibrary)
 *     Native.load("mylib", MyNativeLibrary.class);
 *

 *

 * By convention, method names are identical to the native names, although you
 * can map java names to different native names by providing a
 * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}
 * in the options map passed to the
 * {@link Native#load(String, Class, Map)} call.
 *

 * Although the names for structures and structure fields may be chosen
 * arbitrarily, they should correspond as closely as possible to the native
 * definitions.  The same is true for parameter names.
 *

 * This interface supports multiple, concurrent invocations of any library
 * methods on the Java side.  Check your library documentation for its
 * multi-threading requirements on the native side.  If a library is not safe
 * for simultaneous multi-threaded access, consider using
 * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded
 * access to the native code.
 *

 * Optional fields

 * Interface options will be automatically propagated to structures defined
 * within the library provided a call to
 * {@link Native#load(String,Class,Map)} is made prior to instantiating
 * any of those structures.  One common way of ensuring this is to declare
 * an INSTANCE field in the interface which holds the
 * load result.
 *

 * OPTIONS (an instance of {@link Map}),
 * TYPE_MAPPER (an instance of {@link TypeMapper}),
 * STRUCTURE_ALIGNMENT (one of the alignment types defined in
 * {@link Structure}), and STRING_ENCODING (a {@link String}) may also
 * be defined.  If no instance of the interface has been instantiated, these
 * fields will be used to determine customization settings for structures and
 * methods defined within the interface.
 *

 *
 * @author  Todd Fast, example@nnthink.com
 * @author  Timothy Wall, example@nnthink.com
 */
public interface Library {

    /**
     * Option key for a {@link TypeMapper} for the library.
     */
    String OPTION_TYPE_MAPPER = "type-mapper";

    /**
     * Option key for a {@link FunctionMapper} for the library.
     */
    String OPTION_FUNCTION_MAPPER = "function-mapper";

    /**
     * Option key for an {@link InvocationMapper} for the library.
     */
    String OPTION_INVOCATION_MAPPER = "invocation-mapper";

    /**
     * Option key for structure alignment type ({@link Integer}), which should
     * be one of the predefined alignment types in {@link Structure}.
     */
    String OPTION_STRUCTURE_ALIGNMENT = "structure-alignment";

    /**
     *
Option key for per-library String encoding.  This affects conversions
     * between Java unicode and native (const char*) strings (as
     * arguments or Structure fields).
     *

     * Defaults to {@link Native#getDefaultStringEncoding()}.
     */
    String OPTION_STRING_ENCODING = "string-encoding";

    /**
     * Option key for a boolean flag to allow any Java class instance as a
     *        parameter.  If no type mapper is found, the object is passed as a
     *        pointer.
     *        NOTE: This is for use with raw JNI interactions via the
     *        JNIEnv data structure.
     */
    String OPTION_ALLOW_OBJECTS = "allow-objects";

    /**
     * Calling convention for the entire library.
     */
    String OPTION_CALLING_CONVENTION = "calling-convention";

    /**
     * Flags to use when opening the native library (see {@link Native#open(String,int)})
     */
    String OPTION_OPEN_FLAGS = "open-flags";

    /**
     *
Class loader to use when searching for native libraries on the
     * resource path (classpath).  If not provided the current thread's
     * context class loader is used.

     * If extracted from the resource path (i.e. bundled in a jar file), the
     * loaded library's lifespan will mirror that of the class loader, which
     * means you can use the same library in isolated contexts without
     * conflict.
     */
    String OPTION_CLASSLOADER = "classloader";

    static class Handler implements InvocationHandler {

        static final Method OBJECT_TOSTRING;

        static final Method OBJECT_HASHCODE;

        static final Method OBJECT_EQUALS;

        static {
            try {
                OBJECT_TOSTRING = Object.class.getMethod("toString");
                OBJECT_HASHCODE = Object.class.getMethod("hashCode");
                OBJECT_EQUALS = Object.class.getMethod("equals", Object.class);
            } catch (Exception e) {
                throw new Error("Error retrieving Object.toString() method");
            }
        }

        /**
         * FunctionInfo has to be immutable to to make the object visible
         * to other threads fully initialized. This is a prerequisite for
         * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}
         */
        private static final class FunctionInfo {

            final InvocationHandler handler;

            final Function function;

            final boolean isVarArgs;

            final Object methodHandle;

            final Map<String, ?> options;

            final Class<?>[] parameterTypes;

            FunctionInfo(Object mh) {
                this.handler = null;
                this.function = null;
                this.isVarArgs = false;
                this.options = null;
                this.parameterTypes = null;
                this.methodHandle = mh;
            }

            FunctionInfo(InvocationHandler handler, Function function, Class<?>[] parameterTypes, boolean isVarArgs, Map<String, ?> options) {
                this.handler = handler;
                this.function = function;
                this.isVarArgs = isVarArgs;
                this.options = options;
                this.parameterTypes = parameterTypes;
                this.methodHandle = null;
            }
        }

        private final NativeLibrary nativeLibrary;

        private final Class<?> interfaceClass;

        // Library invocation options
        private final Map<String, Object> options;

        private final InvocationMapper invocationMapper;

        private final Map<Method, FunctionInfo> functions = new WeakHashMap<Method, FunctionInfo>();

        public Handler(String libname, Class<?> interfaceClass, Map<String, ?> options) {
            if (libname != null && "".equals(libname.trim())) {
                throw new IllegalArgumentException("Invalid library name \"" + libname + "\"");
            }
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(libname + " does not implement an interface: " + interfaceClass.getName());
            }
            this.interfaceClass = interfaceClass;
            this.options = new HashMap<String, Object>(options);
            int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;
            if (this.options.get(OPTION_CALLING_CONVENTION) == null) {
                this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));
            }
            if (this.options.get(OPTION_CLASSLOADER) == null) {
                this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());
            }
            this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);
            invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);
        }

        public NativeLibrary getNativeLibrary() {
            return nativeLibrary;
        }

        public String getLibraryName()

        public Class<?> getInterfaceClass() {
            return interfaceClass;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {
            // Intercept Object methods
            if (OBJECT_TOSTRING.equals(method)) {
                return "Proxy interface to " + nativeLibrary;
            } else if (OBJECT_HASHCODE.equals(method)) {
                return Integer.valueOf(hashCode());
            } else if (OBJECT_EQUALS.equals(method)) {
                Object o = inArgs[0];
                if (o != null && Proxy.isProxyClass(o.getClass())) {
                    return Function.valueOf(Proxy.getInvocationHandler(o) == this);
                }
                return Boolean.FALSE;
            }
            // Using the double-checked locking pattern to speed up function calls
            FunctionInfo f = functions.get(method);
            if (f == null) {
                synchronized (functions) {
                    f = functions.get(method);
                    if (f == null) {
                        boolean isDefault = ReflectionUtils.isDefault(method);
                        if (!isDefault) {
                            boolean isVarArgs = Function.isVarArgs(method);
                            InvocationHandler handler = null;
                            if (invocationMapper != null) {
                                handler = invocationMapper.getInvocationHandler(nativeLibrary, method);
                            }
                            Function function = null;
                            Class<?>[] parameterTypes = null;
                            Map<String, Object> options = null;
                            if (handler == null) {
                                // Find the function to invoke
                                function = nativeLibrary.getFunction(method.getName(), method);
                                parameterTypes = method.getParameterTypes();
                                options = new HashMap<String, Object>(this.options);
                                options.put(Function.OPTION_INVOKING_METHOD, method);
                            }
                            f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);
                        } else {
                            f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));
                        }
                        functions.put(method, f);
                    }
                }
            }
            if (f.methodHandle != null) {
                return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);
            } else {
                if (f.isVarArgs) {
                    inArgs = Function.concatenateVarArgs(inArgs);
                }
                if (f.handler != null) {
                    return f.handler.invoke(proxy, method, inArgs);
                }
                return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);
            }
        }
    }
}


package com.sun.jna;

import com.sun.jna.internal.ReflectionUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Derive from this interface for all native library definitions.
 *
 * Define an instance of your library like this:
 *

 * MyNativeLibrary INSTANCE = (MyNativeLibrary)
 *     Native.load("mylib", MyNativeLibrary.class);
 *

 *

 * By convention, method names are identical to the native names, although you
 * can map java names to different native names by providing a
 * {@link FunctionMapper} as a value for key {@link #OPTION_FUNCTION_MAPPER}
 * in the options map passed to the
 * {@link Native#load(String, Class, Map)} call.
 *

 * Although the names for structures and structure fields may be chosen
 * arbitrarily, they should correspond as closely as possible to the native
 * definitions.  The same is true for parameter names.
 *

 * This interface supports multiple, concurrent invocations of any library
 * methods on the Java side.  Check your library documentation for its
 * multi-threading requirements on the native side.  If a library is not safe
 * for simultaneous multi-threaded access, consider using
 * {@link Native#synchronizedLibrary} to prevent simultaneous multi-threaded
 * access to the native code.
 *

 * Optional fields

 * Interface options will be automatically propagated to structures defined
 * within the library provided a call to
 * {@link Native#load(String,Class,Map)} is made prior to instantiating
 * any of those structures.  One common way of ensuring this is to declare
 * an INSTANCE field in the interface which holds the
 * load result.
 *

 * OPTIONS (an instance of {@link Map}),
 * TYPE_MAPPER (an instance of {@link TypeMapper}),
 * STRUCTURE_ALIGNMENT (one of the alignment types defined in
 * {@link Structure}), and STRING_ENCODING (a {@link String}) may also
 * be defined.  If no instance of the interface has been instantiated, these
 * fields will be used to determine customization settings for structures and
 * methods defined within the interface.
 *

 *
 * @author  Todd Fast, example@nnthink.com
 * @author  Timothy Wall, example@nnthink.com
 */
public interface Library {

    /**
     * Option key for a {@link TypeMapper} for the library.
     */
    String OPTION_TYPE_MAPPER = "type-mapper";

    /**
     * Option key for a {@link FunctionMapper} for the library.
     */
    String OPTION_FUNCTION_MAPPER = "function-mapper";

    /**
     * Option key for an {@link InvocationMapper} for the library.
     */
    String OPTION_INVOCATION_MAPPER = "invocation-mapper";

    /**
     * Option key for structure alignment type ({@link Integer}), which should
     * be one of the predefined alignment types in {@link Structure}.
     */
    String OPTION_STRUCTURE_ALIGNMENT = "structure-alignment";

    /**
     *
Option key for per-library String encoding.  This affects conversions
     * between Java unicode and native (const char*) strings (as
     * arguments or Structure fields).
     *

     * Defaults to {@link Native#getDefaultStringEncoding()}.
     */
    String OPTION_STRING_ENCODING = "string-encoding";

    /**
     * Option key for a boolean flag to allow any Java class instance as a
     *        parameter.  If no type mapper is found, the object is passed as a
     *        pointer.
     *        NOTE: This is for use with raw JNI interactions via the
     *        JNIEnv data structure.
     */
    String OPTION_ALLOW_OBJECTS = "allow-objects";

    /**
     * Calling convention for the entire library.
     */
    String OPTION_CALLING_CONVENTION = "calling-convention";

    /**
     * Flags to use when opening the native library (see {@link Native#open(String,int)})
     */
    String OPTION_OPEN_FLAGS = "open-flags";

    /**
     *
Class loader to use when searching for native libraries on the
     * resource path (classpath).  If not provided the current thread's
     * context class loader is used.

     * If extracted from the resource path (i.e. bundled in a jar file), the
     * loaded library's lifespan will mirror that of the class loader, which
     * means you can use the same library in isolated contexts without
     * conflict.
     */
    String OPTION_CLASSLOADER = "classloader";

    static class Handler implements InvocationHandler {

        static final Method OBJECT_TOSTRING;

        static final Method OBJECT_HASHCODE;

        static final Method OBJECT_EQUALS;

        static {
            try {
                OBJECT_TOSTRING = Object.class.getMethod("toString");
                OBJECT_HASHCODE = Object.class.getMethod("hashCode");
                OBJECT_EQUALS = Object.class.getMethod("equals", Object.class);
            } catch (Exception e) {
                throw new Error("Error retrieving Object.toString() method");
            }
        }

        /**
         * FunctionInfo has to be immutable to to make the object visible
         * to other threads fully initialized. This is a prerequisite for
         * using the class in the double checked locking scenario of {@link Handler#invoke(Object, Method, Object[])}
         */
        private static final class FunctionInfo {

            final InvocationHandler handler;

            final Function function;

            final boolean isVarArgs;

            final Object methodHandle;

            final Map<String, ?> options;

            final Class<?>[] parameterTypes;

            FunctionInfo(Object mh) {
                this.handler = null;
                this.function = null;
                this.isVarArgs = false;
                this.options = null;
                this.parameterTypes = null;
                this.methodHandle = mh;
            }

            FunctionInfo(InvocationHandler handler, Function function, Class<?>[] parameterTypes, boolean isVarArgs, Map<String, ?> options) {
                this.handler = handler;
                this.function = function;
                this.isVarArgs = isVarArgs;
                this.options = options;
                this.parameterTypes = parameterTypes;
                this.methodHandle = null;
            }
        }

        private final NativeLibrary nativeLibrary;

        private final Class<?> interfaceClass;

        // Library invocation options
        private final Map<String, Object> options;

        private final InvocationMapper invocationMapper;

        private final Map<Method, FunctionInfo> functions = new WeakHashMap<Method, FunctionInfo>();

        public Handler(String libname, Class<?> interfaceClass, Map<String, ?> options) {
            if (libname != null && "".equals(libname.trim())) {
                throw new IllegalArgumentException("Invalid library name \"" + libname + "\"");
            }
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(libname + " does not implement an interface: " + interfaceClass.getName());
            }
            this.interfaceClass = interfaceClass;
            this.options = new HashMap<String, Object>(options);
            int callingConvention = AltCallingConvention.class.isAssignableFrom(interfaceClass) ? Function.ALT_CONVENTION : Function.C_CONVENTION;
            if (this.options.get(OPTION_CALLING_CONVENTION) == null) {
                this.options.put(OPTION_CALLING_CONVENTION, Integer.valueOf(callingConvention));
            }
            if (this.options.get(OPTION_CLASSLOADER) == null) {
                this.options.put(OPTION_CLASSLOADER, interfaceClass.getClassLoader());
            }
            this.nativeLibrary = NativeLibrary.getInstance(libname, this.options);
            invocationMapper = (InvocationMapper) this.options.get(OPTION_INVOCATION_MAPPER);
        }

        public NativeLibrary getNativeLibrary() {
            return nativeLibrary;
        }

        public String getLibraryName() {
            return nativeLi

        }

        public Class<?> getInterfaceClass() {
            return interfaceClass;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] inArgs) throws Throwable {
            // Intercept Object methods
            if (OBJECT_TOSTRING.equals(method)) {
                return "Proxy interface to " + nativeLibrary;
            } else if (OBJECT_HASHCODE.equals(method)) {
                return Integer.valueOf(hashCode());
            } else if (OBJECT_EQUALS.equals(method)) {
                Object o = inArgs[0];
                if (o != null && Proxy.isProxyClass(o.getClass())) {
                    return Function.valueOf(Proxy.getInvocationHandler(o) == this);
                }
                return Boolean.FALSE;
            }
            // Using the double-checked locking pattern to speed up function calls
            FunctionInfo f = functions.get(method);
            if (f == null) {
                synchronized (functions) {
                    f = functions.get(method);
                    if (f == null) {
                        boolean isDefault = ReflectionUtils.isDefault(method);
                        if (!isDefault) {
                            boolean isVarArgs = Function.isVarArgs(method);
                            InvocationHandler handler = null;
                            if (invocationMapper != null) {
                                handler = invocationMapper.getInvocationHandler(nativeLibrary, method);
                            }
                            Function function = null;
                            Class<?>[] parameterTypes = null;
                            Map<String, Object> options = null;
                            if (handler == null) {
                                // Find the function to invoke
                                function = nativeLibrary.getFunction(method.getName(), method);
                                parameterTypes = method.getParameterTypes();
                                options = new HashMap<String, Object>(this.options);
                                options.put(Function.OPTION_INVOKING_METHOD, method);
                            }
                            f = new FunctionInfo(handler, function, parameterTypes, isVarArgs, options);
                        } else {
                            f = new FunctionInfo(ReflectionUtils.getMethodHandle(method));
                        }
                        functions.put(method, f);
                    }
                }
            }
            if (f.methodHandle != null) {
                return ReflectionUtils.invokeDefaultMethod(proxy, f.methodHandle, inArgs);
            } else {
                if (f.isVarArgs) {
                    inArgs = Function.concatenateVarArgs(inArgs);
                }
                if (f.handler != null) {
                    return f.handler.invoke(proxy, method, inArgs);
                }
                return f.function.invoke(method, f.parameterTypes, method.getReturnType(), inArgs, f.options);
            }
        }
    }
}