Search in sources :

Example 31 with GroovyClassLoader

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

the class ASTTransformationVisitor method doAddGlobalTransforms.

private static void doAddGlobalTransforms(ASTTransformationsContext context, boolean isFirstScan) {
    final CompilationUnit compilationUnit = context.getCompilationUnit();
    GroovyClassLoader transformLoader = compilationUnit.getTransformLoader();
    Map<String, URL> transformNames = new LinkedHashMap<String, URL>();
    try {
        Enumeration<URL> globalServices = transformLoader.getResources("META-INF/services/org.codehaus.groovy.transform.ASTTransformation");
        while (globalServices.hasMoreElements()) {
            URL service = globalServices.nextElement();
            String className;
            BufferedReader svcIn = null;
            try {
                svcIn = new BufferedReader(new InputStreamReader(service.openStream(), "UTF-8"));
                try {
                    className = svcIn.readLine();
                } catch (IOException ioe) {
                    compilationUnit.getErrorCollector().addError(new SimpleMessage("IOException reading the service definition at " + service.toExternalForm() + " because of exception " + ioe.toString(), null));
                    continue;
                }
                Set<String> disabledGlobalTransforms = compilationUnit.getConfiguration().getDisabledGlobalASTTransformations();
                if (disabledGlobalTransforms == null)
                    disabledGlobalTransforms = Collections.emptySet();
                while (className != null) {
                    if (!className.startsWith("#") && className.length() > 0) {
                        if (!disabledGlobalTransforms.contains(className)) {
                            if (transformNames.containsKey(className)) {
                                if (!service.equals(transformNames.get(className))) {
                                    compilationUnit.getErrorCollector().addWarning(WarningMessage.POSSIBLE_ERRORS, "The global transform for class " + className + " is defined in both " + transformNames.get(className).toExternalForm() + " and " + service.toExternalForm() + " - the former definition will be used and the latter ignored.", null, null);
                                }
                            } else {
                                transformNames.put(className, service);
                            }
                        }
                    }
                    try {
                        className = svcIn.readLine();
                    } catch (IOException ioe) {
                        compilationUnit.getErrorCollector().addError(new SimpleMessage("IOException reading the service definition at " + service.toExternalForm() + " because of exception " + ioe.toString(), null));
                        // noinspection UnnecessaryContinue
                        continue;
                    }
                }
            } finally {
                if (svcIn != null)
                    svcIn.close();
            }
        }
    } catch (IOException e) {
        // FIXME the warning message will NPE with what I have :(
        compilationUnit.getErrorCollector().addError(new SimpleMessage("IO Exception attempting to load global transforms:" + e.getMessage(), null));
    }
    try {
        // test for 1.5 JVM
        Class.forName("java.lang.annotation.Annotation");
    } catch (Exception e) {
        // we failed, notify the user
        StringBuilder sb = new StringBuilder();
        sb.append("Global ASTTransformations are not enabled in retro builds of groovy.\n");
        sb.append("The following transformations will be ignored:");
        for (Map.Entry<String, URL> entry : transformNames.entrySet()) {
            sb.append('\t');
            sb.append(entry.getKey());
            sb.append('\n');
        }
        compilationUnit.getErrorCollector().addWarning(new WarningMessage(WarningMessage.POSSIBLE_ERRORS, sb.toString(), null, null));
        return;
    }
    // can be added for only for new transforms that have come in
    if (isFirstScan) {
        for (Map.Entry<String, URL> entry : transformNames.entrySet()) {
            context.getGlobalTransformNames().add(entry.getKey());
        }
        addPhaseOperationsForGlobalTransforms(context.getCompilationUnit(), transformNames, isFirstScan);
    } else {
        Iterator<Map.Entry<String, URL>> it = transformNames.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, URL> entry = it.next();
            if (!context.getGlobalTransformNames().add(entry.getKey())) {
                // phase operations for this transform class have already been added before, so remove from current scan cycle
                it.remove();
            }
        }
        addPhaseOperationsForGlobalTransforms(context.getCompilationUnit(), transformNames, isFirstScan);
    }
}
Also used : WarningMessage(org.codehaus.groovy.control.messages.WarningMessage) InputStreamReader(java.io.InputStreamReader) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) IOException(java.io.IOException) URL(java.net.URL) IOException(java.io.IOException) GroovyClassLoader(groovy.lang.GroovyClassLoader) BufferedReader(java.io.BufferedReader)

Example 32 with GroovyClassLoader

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

the class Groovy2365Bug method testDeadlock.

public void testDeadlock() {
    String path = createData();
    try {
        System.out.println("Test started");
        for (int i = 0; i != 100; ++i) {
            System.out.println("Iter " + i);
            final GroovyClassLoader groovyLoader = new GroovyClassLoader();
            groovyLoader.addClasspath(path);
            Class _script1Class = null;
            try {
                _script1Class = groovyLoader.loadClass("Script1", true, true);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            final Class script1Class = _script1Class;
            // setup two threads to try a deadlock
            // thread one: newInstance script foo
            final boolean[] completed = new boolean[2];
            Thread thread1 = new Thread() {

                public void run() {
                    try {
                        Script script = (Script) script1Class.newInstance();
                        script.run();
                        completed[0] = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            Thread thread2 = new Thread() {

                public void run() {
                    try {
                        Class cls = groovyLoader.loadClass("Script2", true, true);
                        Script script = (Script) cls.newInstance();
                        script.run();
                        completed[1] = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            // let's see if we get a deadlock
            thread2.start();
            thread1.start();
            try {
                thread1.join(5000);
                thread2.join(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            assertTrue("Potentially deadlock", completed[0] && completed[1]);
        }
    } finally {
        ResourceGroovyMethods.deleteDir(new File(path));
    }
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) Script(groovy.lang.Script) File(java.io.File)

Example 33 with GroovyClassLoader

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

the class GenerateStubsTask method compile.

@Override
protected void compile() {
    GroovyClassLoader gcl = createClassLoader();
    JavaStubCompilationUnit cu = new JavaStubCompilationUnit(config, gcl, destdir);
    int count = 0;
    String[] list = src.list();
    for (int i = 0; i < list.length; i++) {
        File basedir = getProject().resolveFile(list[i]);
        if (!basedir.exists()) {
            throw new BuildException("Source directory does not exist: " + basedir, getLocation());
        }
        DirectoryScanner scanner = getDirectoryScanner(basedir);
        String[] includes = scanner.getIncludedFiles();
        log.debug("Including files from: " + basedir);
        for (int j = 0; j < includes.length; j++) {
            log.debug("    " + includes[j]);
            File file = new File(basedir, includes[j]);
            cu.addSource(file);
            // Increment the count for each non/java src we found
            if (!includes[j].endsWith(".java")) {
                count++;
            }
        }
    }
    if (count > 0) {
        log.info("Generating " + count + " Java stub" + (count > 1 ? "s" : "") + " to " + destdir);
        cu.compile();
        log.info("Generated " + cu.getStubCount() + " Java stub(s)");
    } else {
        log.info("No sources found for stub generation");
    }
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) JavaStubCompilationUnit(org.codehaus.groovy.tools.javac.JavaStubCompilationUnit) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Example 34 with GroovyClassLoader

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

the class JdkDynamicProxyTest method testJdkDynamicProxySameLoader.

public void testJdkDynamicProxySameLoader() throws Exception {
    // Instantiate all beans.
    final GroovyClassLoader loader = new GroovyClassLoader();
    JdkDynamicProxyServiceBean sb1 = (JdkDynamicProxyServiceBean) JdkDynamicProxyInvocationHandler.getProxiedObject(loader.loadClass("org.codehaus.groovy.runtime.JdkDynamicProxyServiceBeanImpl1").newInstance());
    JdkDynamicProxyServiceBean sb2 = (JdkDynamicProxyServiceBean) JdkDynamicProxyInvocationHandler.getProxiedObject(loader.loadClass("org.codehaus.groovy.runtime.JdkDynamicProxyServiceBeanImpl2").newInstance());
    // Manually wire beans together.
    sb1.setJdkDynamicProxyServiceBean(sb2);
    assertEquals("SERVICE", sb1.doService());
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader)

Example 35 with GroovyClassLoader

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

the class ClassNodeResolver method tryAsLoaderClassOrScript.

/**
 * This method is used to realize the lookup of a class using the compilation
 * unit class loader. Should no class be found we fall back to a script lookup.
 * If a class is found we check if there is also a script and maybe use that
 * one in case it is newer.<p/>
 *
 * Two class search strategies are possible: by ASM decompilation or by usual Java classloading.
 * The latter is slower but is unavoidable for scripts executed in dynamic environments where
 * the referenced classes might only be available in the classloader, not on disk.
 */
private LookupResult tryAsLoaderClassOrScript(String name, CompilationUnit compilationUnit) {
    GroovyClassLoader loader = compilationUnit.getClassLoader();
    Map<String, Boolean> options = compilationUnit.configuration.getOptimizationOptions();
    boolean useAsm = !Boolean.FALSE.equals(options.get("asmResolving"));
    boolean useClassLoader = !Boolean.FALSE.equals(options.get("classLoaderResolving"));
    LookupResult result = useAsm ? findDecompiled(name, compilationUnit, loader) : null;
    if (result != null) {
        return result;
    }
    if (!useClassLoader) {
        return tryAsScript(name, compilationUnit, null);
    }
    return findByClassLoading(name, compilationUnit, loader);
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader)

Aggregations

GroovyClassLoader (groovy.lang.GroovyClassLoader)136 File (java.io.File)28 GroovyObject (groovy.lang.GroovyObject)19 Test (org.junit.jupiter.api.Test)18 IOException (java.io.IOException)15 HashMap (java.util.HashMap)15 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)14 Map (java.util.Map)12 Binding (groovy.lang.Binding)10 URL (java.net.URL)10 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)10 BuildException (org.apache.tools.ant.BuildException)9 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)9 ClassNode (org.codehaus.groovy.ast.ClassNode)9 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)9 DefaultGrailsApplication (grails.core.DefaultGrailsApplication)8 GrailsApplication (grails.core.GrailsApplication)8 AnnotatedNode (org.codehaus.groovy.ast.AnnotatedNode)8 ArtefactHandler (grails.core.ArtefactHandler)7 SimpleMessage (org.codehaus.groovy.control.messages.SimpleMessage)7