Search in sources :

Example 86 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project groovy by apache.

the class GroovyTypeCheckingExtensionSupport method setup.

@Override
public void setup() {
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass("org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingDSL");
    ImportCustomizer ic = new ImportCustomizer();
    ic.addStarImports("org.codehaus.groovy.ast.expr");
    ic.addStaticStars("org.codehaus.groovy.ast.ClassHelper");
    ic.addStaticStars("org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport");
    config.addCompilationCustomizers(ic);
    final GroovyClassLoader transformLoader = compilationUnit != null ? compilationUnit.getTransformLoader() : typeCheckingVisitor.getSourceUnit().getClassLoader();
    // since Groovy 2.2, it is possible to use FQCN for type checking extension scripts
    TypeCheckingDSL script = null;
    try {
        Class<?> clazz = transformLoader.loadClass(scriptPath, false, true);
        if (TypeCheckingDSL.class.isAssignableFrom(clazz)) {
            script = (TypeCheckingDSL) clazz.newInstance();
        } else if (TypeCheckingExtension.class.isAssignableFrom(clazz)) {
            // since 2.4, we can also register precompiled type checking extensions which are not scripts
            try {
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(StaticTypeCheckingVisitor.class);
                TypeCheckingExtension extension = (TypeCheckingExtension) declaredConstructor.newInstance(typeCheckingVisitor);
                typeCheckingVisitor.addTypeCheckingExtension(extension);
                extension.setup();
                return;
            } catch (InstantiationException e) {
                addLoadingError(config);
            } catch (IllegalAccessException e) {
                addLoadingError(config);
            } catch (NoSuchMethodException e) {
                context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' could not be loaded because it doesn't have a constructor accepting StaticTypeCheckingVisitor.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
            } catch (InvocationTargetException e) {
                addLoadingError(config);
            }
        }
    } catch (ClassNotFoundException e) {
    // silent
    } catch (InstantiationException e) {
        addLoadingError(config);
    } catch (IllegalAccessException e) {
        addLoadingError(config);
    }
    if (script == null) {
        ClassLoader cl = typeCheckingVisitor.getSourceUnit().getClassLoader();
        // cast to prevent incorrect @since 1.7 warning
        InputStream is = ((ClassLoader) transformLoader).getResourceAsStream(scriptPath);
        if (is == null) {
            // fallback to the source unit classloader
            is = cl.getResourceAsStream(scriptPath);
        }
        if (is == null) {
            // fallback to the compiler classloader
            cl = GroovyTypeCheckingExtensionSupport.class.getClassLoader();
            is = cl.getResourceAsStream(scriptPath);
        }
        if (is == null) {
            // if the input stream is still null, we've not found the extension
            context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' was not found on the classpath.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
        }
        try {
            GroovyShell shell = new GroovyShell(transformLoader, new Binding(), config);
            script = (TypeCheckingDSL) shell.parse(new InputStreamReader(is, typeCheckingVisitor.getSourceUnit().getConfiguration().getSourceEncoding()));
        } catch (CompilationFailedException e) {
            throw new GroovyBugError("An unexpected error was thrown during custom type checking", e);
        } catch (UnsupportedEncodingException e) {
            throw new GroovyBugError("Unsupported encoding found in compiler configuration", e);
        }
    }
    if (script != null) {
        script.extension = this;
        script.run();
        List<Closure> list = eventHandlers.get("setup");
        if (list != null) {
            for (Closure closure : list) {
                safeCall(closure);
            }
        }
    }
}
Also used : Closure(groovy.lang.Closure) GroovyBugError(org.codehaus.groovy.GroovyBugError) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyClassLoader(groovy.lang.GroovyClassLoader) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) Binding(groovy.lang.Binding) InputStreamReader(java.io.InputStreamReader) Constructor(java.lang.reflect.Constructor) InputStream(java.io.InputStream) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyShell(groovy.lang.GroovyShell)

Example 87 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project engine by craftercms.

the class SiteContextFactory method getClassLoader.

protected URLClassLoader getClassLoader(SiteContext siteContext) {
    ContentStoreGroovyResourceLoader resourceLoader = new ContentStoreGroovyResourceLoader(siteContext, groovyClassesPath);
    GroovyClassLoader classLoader = new GroovyClassLoader(getClass().getClassLoader());
    classLoader.setResourceLoader(resourceLoader);
    return classLoader;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) ContentStoreGroovyResourceLoader(org.craftercms.engine.util.groovy.ContentStoreGroovyResourceLoader)

Example 88 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project cas by apereo.

the class CoreAuthenticationUtils method newCredentialSelectionPredicate.

/**
 * Gets credential selection predicate.
 *
 * @param selectionCriteria the selection criteria
 * @return the credential selection predicate
 */
public static Predicate<Credential> newCredentialSelectionPredicate(final String selectionCriteria) {
    try {
        if (StringUtils.isBlank(selectionCriteria)) {
            return credential -> true;
        }
        if (selectionCriteria.endsWith(".groovy")) {
            final ResourceLoader loader = new DefaultResourceLoader();
            final Resource resource = loader.getResource(selectionCriteria);
            if (resource != null) {
                final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
                final GroovyClassLoader classLoader = new GroovyClassLoader(Beans.class.getClassLoader(), new CompilerConfiguration(), true);
                final Class<Predicate> clz = classLoader.parseClass(script);
                return clz.getDeclaredConstructor().newInstance();
            }
        }
        final Class predicateClazz = ClassUtils.getClass(selectionCriteria);
        return (Predicate<org.apereo.cas.authentication.Credential>) predicateClazz.getDeclaredConstructor().newInstance();
    } catch (final Exception e) {
        final Predicate<String> predicate = Pattern.compile(selectionCriteria).asPredicate();
        return credential -> predicate.test(credential.getId());
    }
}
Also used : ArrayListMultimap(com.google.common.collect.ArrayListMultimap) ResourceLoader(org.springframework.core.io.ResourceLoader) Predicate(java.util.function.Predicate) Beans(org.apereo.cas.configuration.support.Beans) Multimap(com.google.common.collect.Multimap) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) StringUtils(org.apache.commons.lang3.StringUtils) StandardCharsets(java.nio.charset.StandardCharsets) UtilityClass(lombok.experimental.UtilityClass) IOUtils(org.apache.commons.io.IOUtils) ClassUtils(org.apache.commons.lang3.ClassUtils) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) Pattern(java.util.regex.Pattern) Splitter(com.google.common.base.Splitter) GroovyClassLoader(groovy.lang.GroovyClassLoader) Resource(org.springframework.core.io.Resource) ResourceLoader(org.springframework.core.io.ResourceLoader) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Resource(org.springframework.core.io.Resource) Predicate(java.util.function.Predicate) GroovyClassLoader(groovy.lang.GroovyClassLoader) Beans(org.apereo.cas.configuration.support.Beans) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) UtilityClass(lombok.experimental.UtilityClass) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader)

Example 89 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project cas by apereo.

the class ScriptingUtils method getObjectInstanceFromGroovyResource.

/**
 * Gets object instance from groovy resource.
 *
 * @param <T>             the type parameter
 * @param resource        the resource
 * @param constructorArgs the constructor args
 * @param args            the args
 * @param expectedType    the expected type
 * @return the object instance from groovy resource
 */
public static <T> T getObjectInstanceFromGroovyResource(final Resource resource, final Class[] constructorArgs, final Object[] args, final Class<T> expectedType) {
    try {
        if (resource == null) {
            LOGGER.debug("No groovy script is defined");
            return null;
        }
        final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
        final GroovyClassLoader classLoader = new GroovyClassLoader(ScriptingUtils.class.getClassLoader(), new CompilerConfiguration(), true);
        final Class<T> clazz = classLoader.parseClass(script);
        LOGGER.debug("Preparing constructor arguments [{}] for resource [{}]", args, resource);
        final Constructor<T> ctor = clazz.getDeclaredConstructor(constructorArgs);
        final T result = ctor.newInstance(args);
        if (result != null && !expectedType.isAssignableFrom(result.getClass())) {
            throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + expectedType);
        }
        return result;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Example 90 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project cas by apereo.

the class ScriptingUtils method getGroovyResult.

private static <T> T getGroovyResult(final Resource groovyScript, final String methodName, final Object[] args, final Class<T> clazz, final ClassLoader parent) {
    try (GroovyClassLoader loader = new GroovyClassLoader(parent)) {
        final File groovyFile = groovyScript.getFile();
        if (groovyFile.exists()) {
            final Class<?> groovyClass = loader.parseClass(groovyFile);
            LOGGER.trace("Creating groovy object instance from class [{}]", groovyFile.getCanonicalPath());
            final GroovyObject groovyObject = (GroovyObject) groovyClass.getDeclaredConstructor().newInstance();
            LOGGER.trace("Executing groovy script's [{}] method, with parameters [{}]", methodName, args);
            final Object result = groovyObject.invokeMethod(methodName, args);
            LOGGER.trace("Results returned by the groovy script are [{}]", result);
            if (result != null && !clazz.isAssignableFrom(result.getClass())) {
                throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
            }
            return (T) result;
        }
        LOGGER.trace("Groovy script at [{}] does not exist", groovyScript);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovyObject(groovy.lang.GroovyObject) File(java.io.File) GroovyObject(groovy.lang.GroovyObject)

Aggregations

GroovyClassLoader (groovy.lang.GroovyClassLoader)126 File (java.io.File)26 GroovyObject (groovy.lang.GroovyObject)17 Test (org.junit.jupiter.api.Test)17 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)13 IOException (java.io.IOException)11 Binding (groovy.lang.Binding)10 URL (java.net.URL)10 HashMap (java.util.HashMap)10 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)10 Map (java.util.Map)9 DefaultGrailsApplication (grails.core.DefaultGrailsApplication)8 GrailsApplication (grails.core.GrailsApplication)8 BuildException (org.apache.tools.ant.BuildException)8 ArtefactHandler (grails.core.ArtefactHandler)7 GroovyShell (groovy.lang.GroovyShell)7 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)7 SimpleMessage (org.codehaus.groovy.control.messages.SimpleMessage)7 Script (groovy.lang.Script)6 Decorator (com.opensymphony.module.sitemesh.Decorator)5