Search in sources :

Example 61 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 62 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 63 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 64 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 65 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project midpoint by Evolveum.

the class GroovyScriptEvaluator method createGroovyLoader.

private GroovyClassLoader createGroovyLoader(ScriptExpressionProfile expressionProfile, ScriptExpressionEvaluationContext context) throws SecurityViolationException {
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration(CompilerConfiguration.DEFAULT);
    configureCompiler(compilerConfiguration, expressionProfile, context);
    return new GroovyClassLoader(GroovyScriptEvaluator.class.getClassLoader(), compilerConfiguration);
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration)

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