Search in sources :

Example 91 with GroovyClassLoader

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

the class ApiGroovyCompiler method execute.

@Override
public WorkResult execute(final GroovyJavaJointCompileSpec spec) {
    GroovySystemLoaderFactory groovySystemLoaderFactory = new GroovySystemLoaderFactory();
    ClassLoader compilerClassLoader = this.getClass().getClassLoader();
    GroovySystemLoader compilerGroovyLoader = groovySystemLoaderFactory.forClassLoader(compilerClassLoader);
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.setVerbose(spec.getGroovyCompileOptions().isVerbose());
    configuration.setSourceEncoding(spec.getGroovyCompileOptions().getEncoding());
    configuration.setTargetBytecode(spec.getTargetCompatibility());
    configuration.setTargetDirectory(spec.getDestinationDir());
    canonicalizeValues(spec.getGroovyCompileOptions().getOptimizationOptions());
    if (spec.getGroovyCompileOptions().getConfigurationScript() != null) {
        applyConfigurationScript(spec.getGroovyCompileOptions().getConfigurationScript(), configuration);
    }
    try {
        configuration.setOptimizationOptions(spec.getGroovyCompileOptions().getOptimizationOptions());
    } catch (NoSuchMethodError ignored) {
    /* method was only introduced in Groovy 1.8 */
    }
    Map<String, Object> jointCompilationOptions = new HashMap<String, Object>();
    final File stubDir = spec.getGroovyCompileOptions().getStubDir();
    stubDir.mkdirs();
    jointCompilationOptions.put("stubDir", stubDir);
    jointCompilationOptions.put("keepStubs", spec.getGroovyCompileOptions().isKeepStubs());
    configuration.setJointCompilationOptions(jointCompilationOptions);
    ClassLoader classPathLoader;
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.0")) < 0) {
        // using a transforming classloader is only required for older buggy Groovy versions
        classPathLoader = new GroovyCompileTransformingClassLoader(getExtClassLoader(), new DefaultClassPath(spec.getCompileClasspath()));
    } else {
        classPathLoader = new DefaultClassLoaderFactory().createIsolatedClassLoader(new DefaultClassPath(spec.getCompileClasspath()));
    }
    GroovyClassLoader compileClasspathClassLoader = new GroovyClassLoader(classPathLoader, null);
    GroovySystemLoader compileClasspathLoader = groovySystemLoaderFactory.forClassLoader(classPathLoader);
    FilteringClassLoader.Spec groovyCompilerClassLoaderSpec = new FilteringClassLoader.Spec();
    groovyCompilerClassLoaderSpec.allowPackage("org.codehaus.groovy");
    groovyCompilerClassLoaderSpec.allowPackage("groovy");
    // Disallow classes from Groovy Jar that reference external classes. Such classes must be loaded from astTransformClassLoader,
    // or a NoClassDefFoundError will occur. Essentially this is drawing a line between the Groovy compiler and the Groovy
    // library, albeit only for selected classes that run a high risk of being statically referenced from a transform.
    groovyCompilerClassLoaderSpec.disallowClass("groovy.util.GroovyTestCase");
    groovyCompilerClassLoaderSpec.disallowPackage("groovy.servlet");
    FilteringClassLoader groovyCompilerClassLoader = new FilteringClassLoader(GroovyClassLoader.class.getClassLoader(), groovyCompilerClassLoaderSpec);
    // AST transforms need their own class loader that shares compiler classes with the compiler itself
    final GroovyClassLoader astTransformClassLoader = new GroovyClassLoader(groovyCompilerClassLoader, null);
    // where the transform class is loaded from)
    for (File file : spec.getCompileClasspath()) {
        astTransformClassLoader.addClasspath(file.getPath());
    }
    JavaAwareCompilationUnit unit = new JavaAwareCompilationUnit(configuration, compileClasspathClassLoader) {

        @Override
        public GroovyClassLoader getTransformLoader() {
            return astTransformClassLoader;
        }
    };
    final boolean shouldProcessAnnotations = shouldProcessAnnotations(spec);
    if (shouldProcessAnnotations) {
        // If an annotation processor is detected, we need to force Java stub generation, so the we can process annotations on Groovy classes
        // We are forcing stub generation by tricking the groovy compiler into thinking there are java files to compile.
        // All java files are just passed to the compile method of the JavaCompiler and aren't processed internally by the Groovy Compiler.
        // Since we're maintaining our own list of Java files independent of what's passed by the Groovy compiler, adding a non-existent java file
        // to the sources won't cause any issues.
        unit.addSources(new File[] { new File("ForceStubGeneration.java") });
    }
    // Sort source files to work around https://issues.apache.org/jira/browse/GROOVY-7966
    File[] sortedSourceFiles = Iterables.toArray(spec.getSource(), File.class);
    Arrays.sort(sortedSourceFiles);
    unit.addSources(sortedSourceFiles);
    unit.setCompilerFactory(new JavaCompilerFactory() {

        public JavaCompiler createCompiler(final CompilerConfiguration config) {
            return new JavaCompiler() {

                public void compile(List<String> files, CompilationUnit cu) {
                    if (shouldProcessAnnotations) {
                        // In order for the Groovy stubs to have annotation processors invoked against them, they must be compiled as source.
                        // Classes compiled as a result of being on the -sourcepath do not have the annotation processor run against them
                        spec.setSource(spec.getSource().plus(new SimpleFileCollection(stubDir).getAsFileTree()));
                    } else {
                        // When annotation processing isn't required, it's better to add the Groovy stubs as part of the source path.
                        // This allows compilations to complete faster, because only the Groovy stubs that are needed by the java source are compiled.
                        ImmutableList.Builder<File> sourcepathBuilder = ImmutableList.builder();
                        sourcepathBuilder.add(stubDir);
                        if (spec.getCompileOptions().getSourcepath() != null) {
                            sourcepathBuilder.addAll(spec.getCompileOptions().getSourcepath());
                        }
                        spec.getCompileOptions().setSourcepath(sourcepathBuilder.build());
                    }
                    spec.setSource(spec.getSource().filter(new Spec<File>() {

                        public boolean isSatisfiedBy(File file) {
                            return hasExtension(file, ".java");
                        }
                    }));
                    try {
                        javaCompiler.execute(spec);
                    } catch (CompilationFailedException e) {
                        cu.getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(), cu));
                    }
                }
            };
        }
    });
    try {
        unit.compile();
    } catch (org.codehaus.groovy.control.CompilationFailedException e) {
        System.err.println(e.getMessage());
        // Explicit flush, System.err is an auto-flushing PrintWriter unless it is replaced.
        System.err.flush();
        throw new CompilationFailedException();
    } finally {
        // Remove compile and AST types from the Groovy loader
        compilerGroovyLoader.discardTypesFrom(classPathLoader);
        compilerGroovyLoader.discardTypesFrom(astTransformClassLoader);
        // Discard the compile loader
        compileClasspathLoader.shutdown();
    }
    return WorkResults.didWork(true);
}
Also used : HashMap(java.util.HashMap) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) GroovyClassLoader(groovy.lang.GroovyClassLoader) SimpleFileCollection(org.gradle.api.internal.file.collections.SimpleFileCollection) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovySystemLoader(org.gradle.api.internal.classloading.GroovySystemLoader) GroovySystemLoaderFactory(org.gradle.api.internal.classloading.GroovySystemLoaderFactory) DefaultClassLoaderFactory(org.gradle.internal.classloader.DefaultClassLoaderFactory) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) CompilationUnit(org.codehaus.groovy.control.CompilationUnit) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) JavaCompiler(org.codehaus.groovy.tools.javac.JavaCompiler) JavaCompilerFactory(org.codehaus.groovy.tools.javac.JavaCompilerFactory) VersionNumber(org.gradle.util.VersionNumber) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) Spec(org.gradle.api.specs.Spec) File(java.io.File) DefaultClassPath(org.gradle.internal.classpath.DefaultClassPath)

Example 92 with GroovyClassLoader

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

the class ScriptCompiler method compile.

private static void compile(File dir, File[] files) {
    try {
        final CompilerConfiguration compilerConfiguration = GroovyScript.createCompilerConfiguration();
        compilerConfiguration.setTargetDirectory(dir);
        final CompilationUnit unit = new CompilationUnit(compilerConfiguration, null, new GroovyClassLoader(ScriptingEngine.class.getClassLoader()));
        new FileSystemCompiler(compilerConfiguration, unit).compile(files);
        LogUtils.info("compiled in " + dir + ": " + createNameList(files));
    } catch (Exception e) {
        LogUtils.severe("error compiling in " + dir + createNameList(files), e);
    }
}
Also used : CompilationUnit(org.codehaus.groovy.control.CompilationUnit) GroovyClassLoader(groovy.lang.GroovyClassLoader) FileSystemCompiler(org.codehaus.groovy.tools.FileSystemCompiler) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

Example 93 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project beakerx by twosigma.

the class GroovyClassUtils method getClass.

@Override
protected Class<?> getClass(String name) throws ClassNotFoundException {
    try {
        Class<?> c = super.getClass(name);
        if (c != null)
            return c;
    } catch (Exception e) {
    }
    String fname = classpathscanner.getFileForClass(name);
    if (fname != null) {
        try {
            if (gloader == null)
                gloader = new GroovyClassLoader(loader != null ? loader : getClass().getClassLoader());
            Class<?> groovyClass = gloader.parseClass(new File(fname));
            return groovyClass;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Class<?> aClass = getClass(name, classpathscanner);
    return aClass;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) File(java.io.File)

Example 94 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project xwiki-platform by xwiki.

the class ParseGroovyFromString method parseGroovyFromString.

public Object parseGroovyFromString(String script, XWikiContext context) throws XWikiException {
    prepareCache(context);
    ClassLoader parentClassLoader = (ClassLoader) context.get("parentclassloader");
    try {
        CachedGroovyClass cgc = this.classCache.get(script);
        Class<?> gc;
        if (cgc == null) {
            GroovyClassLoader gcl = (parentClassLoader == null) ? new GroovyClassLoader() : new GroovyClassLoader(parentClassLoader);
            gc = gcl.parseClass(script);
            cgc = new CachedGroovyClass(gc);
            this.classCache.set(script, cgc);
        } else {
            gc = cgc.getGroovyClass();
        }
        return gc.newInstance();
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_GROOVY, XWikiException.ERROR_XWIKI_GROOVY_COMPILE_FAILED, "Failed compiling groovy script", e);
    }
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovyClassLoader(groovy.lang.GroovyClassLoader) XWikiException(com.xpn.xwiki.XWikiException) CacheException(org.xwiki.cache.CacheException) XWikiException(com.xpn.xwiki.XWikiException)

Example 95 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project walkmod-core by walkmod.

the class ScriptProcessor method initialize.

public void initialize(VisitorContext context, Object node) {
    if (engine == null) {
        ScriptEngineManager factory = new ScriptEngineManager(context.getClassLoader());
        engine = factory.getEngineByName(language);
        if (engine instanceof GroovyScriptEngineImpl) {
            ((GroovyScriptEngineImpl) engine).setClassLoader(new GroovyClassLoader(context.getClassLoader(), new CompilerConfiguration()));
        }
    }
    if (queryEngine == null) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("language", "groovy");
        List<String> includes = new LinkedList<String>();
        includes.add("query.alias.groovy");
        parameters.put("includes", includes);
        Object bean = context.getBean("org.walkmod.query.ScriptingQueryEngine", parameters);
        if (bean != null) {
            if (bean instanceof QueryEngine) {
                queryEngine = (QueryEngine) bean;
            }
        } else {
            throw new WalkModException("Query Engine not found");
        }
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("node", node);
    queryEngine.initialize(context, params);
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovyScriptEngineImpl(org.codehaus.groovy.jsr223.GroovyScriptEngineImpl) WalkModException(org.walkmod.exceptions.WalkModException) HashMap(java.util.HashMap) ScriptEngineManager(javax.script.ScriptEngineManager) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) QueryEngine(org.walkmod.query.QueryEngine) LinkedList(java.util.LinkedList)

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