Search in sources :

Example 81 with GroovyClassLoader

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

the class Groovy method execGroovy.

/**
     * Exec the statement.
     *
     * @param txt the groovy source to exec
     * @param out not used?
     */
protected void execGroovy(final String txt, final PrintStream out) {
    log.debug("execGroovy()");
    // Check and ignore empty statements
    if ("".equals(txt.trim())) {
        return;
    }
    log.verbose("Script: " + txt);
    if (classpath != null) {
        log.debug("Explicit Classpath: " + classpath.toString());
    }
    if (fork) {
        log.debug("Using fork mode");
        try {
            createClasspathParts();
            createNewArgs(txt);
            super.setFork(fork);
            super.setClassname(useGroovyShell ? "groovy.lang.GroovyShell" : "org.codehaus.groovy.ant.Groovy");
            configureCompiler();
            super.execute();
        } catch (Exception e) {
            StringWriter writer = new StringWriter();
            new ErrorReporter(e, false).write(new PrintWriter(writer));
            String message = writer.toString();
            throw new BuildException("Script Failed: " + message, e, getLocation());
        }
        return;
    }
    Object mavenPom = null;
    final Project project = getProject();
    final ClassLoader baseClassLoader;
    ClassLoader savedLoader = null;
    final Thread thread = Thread.currentThread();
    boolean maven = "org.apache.commons.grant.GrantProject".equals(project.getClass().getName());
    // treat the case Ant is run through Maven, and
    if (maven) {
        if (contextClassLoader) {
            throw new BuildException("Using setContextClassLoader not permitted when using Maven.", getLocation());
        }
        try {
            final Object propsHandler = project.getClass().getMethod("getPropsHandler").invoke(project);
            final Field contextField = propsHandler.getClass().getDeclaredField("context");
            contextField.setAccessible(true);
            final Object context = contextField.get(propsHandler);
            mavenPom = InvokerHelper.invokeMethod(context, "getProject", EMPTY_OBJECT_ARRAY);
        } catch (Exception e) {
            throw new BuildException("Impossible to retrieve Maven's Ant project: " + e.getMessage(), getLocation());
        }
        // load groovy into "root.maven" classloader instead of "root" so that
        // groovy script can access Maven classes
        baseClassLoader = mavenPom.getClass().getClassLoader();
    } else {
        baseClassLoader = GroovyShell.class.getClassLoader();
    }
    if (contextClassLoader || maven) {
        savedLoader = thread.getContextClassLoader();
        thread.setContextClassLoader(GroovyShell.class.getClassLoader());
    }
    final String scriptName = computeScriptName();
    final GroovyClassLoader classLoader = new GroovyClassLoader(baseClassLoader);
    addClassPathes(classLoader);
    configureCompiler();
    final GroovyShell groovy = new GroovyShell(classLoader, new Binding(), configuration);
    try {
        parseAndRunScript(groovy, txt, mavenPom, scriptName, null, new AntBuilder(this));
    } finally {
        groovy.resetLoadedClasses();
        groovy.getClassLoader().clearCache();
        if (contextClassLoader || maven)
            thread.setContextClassLoader(savedLoader);
    }
}
Also used : Binding(groovy.lang.Binding) AntBuilder(groovy.util.AntBuilder) MissingMethodException(groovy.lang.MissingMethodException) BuildException(org.apache.tools.ant.BuildException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyShell(groovy.lang.GroovyShell) GroovyClassLoader(groovy.lang.GroovyClassLoader) Project(org.apache.tools.ant.Project) Field(java.lang.reflect.Field) ErrorReporter(org.codehaus.groovy.tools.ErrorReporter) StringWriter(java.io.StringWriter) GroovyClassLoader(groovy.lang.GroovyClassLoader) BuildException(org.apache.tools.ant.BuildException) PrintWriter(java.io.PrintWriter)

Example 82 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project opennms by OpenNMS.

the class GroovyRunnerTest method getGroovyClass.

private Class<?> getGroovyClass(String filename) throws IOException {
    GroovyClassLoader gcl = new GroovyClassLoader();
    Class<?> clazz = gcl.parseClass(new File(filename));
    return clazz;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) File(java.io.File)

Example 83 with GroovyClassLoader

use of groovy.lang.GroovyClassLoader in project opennms by OpenNMS.

the class SeleniumMonitor method createGroovyClass.

private Class<?> createGroovyClass(String filename) throws CompilationFailedException, IOException {
    GroovyClassLoader gcl = new GroovyClassLoader();
    String file = System.getProperty("opennms.home") + "/etc/selenium/" + filename;
    System.err.println("File name: " + file);
    return gcl.parseClass(new File(file));
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) File(java.io.File)

Example 84 with GroovyClassLoader

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

the class ClassNodeResolver method tryAsScript.

/**
     * try to find a script using the compilation unit class loader.
     */
private static LookupResult tryAsScript(String name, CompilationUnit compilationUnit, ClassNode oldClass) {
    LookupResult lr = null;
    if (oldClass != null) {
        lr = new LookupResult(null, oldClass);
    }
    if (name.startsWith("java."))
        return lr;
    //TODO: don't ignore inner static classes completely
    if (name.indexOf('$') != -1)
        return lr;
    // try to find a script from classpath*/
    GroovyClassLoader gcl = compilationUnit.getClassLoader();
    URL url = null;
    try {
        url = gcl.getResourceLoader().loadGroovySource(name);
    } catch (MalformedURLException e) {
    // fall through and let the URL be null
    }
    if (url != null && (oldClass == null || isSourceNewer(url, oldClass))) {
        SourceUnit su = compilationUnit.addSource(url);
        return new LookupResult(su, null);
    }
    return lr;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL)

Example 85 with GroovyClassLoader

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

the class Groovy2365Bug method testDeadlock.

public void testDeadlock() {
    String path = createData();
    try {
        for (int i = 0; i != 100; ++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)

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