Search in sources :

Example 16 with Script

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

the class GroovyScriptEngineImpl method eval.

// package-privates
Object eval(Class<?> scriptClass, final ScriptContext ctx) throws ScriptException {
    /*
         * We use the following Binding instance so that global variable lookup
         * will be done in the current ScriptContext instance.
         */
    Binding binding = new Binding(ctx.getBindings(ScriptContext.ENGINE_SCOPE)) {

        @Override
        public Object getVariable(String name) {
            synchronized (ctx) {
                int scope = ctx.getAttributesScope(name);
                if (scope != -1) {
                    return ctx.getAttribute(name, scope);
                }
                // Redirect script output to context writer, if out var is not already provided
                if ("out".equals(name)) {
                    Writer writer = ctx.getWriter();
                    if (writer != null) {
                        return (writer instanceof PrintWriter) ? (PrintWriter) writer : new PrintWriter(writer, true);
                    }
                }
                // Provide access to engine context, if context var is not already provided
                if ("context".equals(name)) {
                    return ctx;
                }
            }
            throw new MissingPropertyException(name, getClass());
        }

        @Override
        public void setVariable(String name, Object value) {
            synchronized (ctx) {
                int scope = ctx.getAttributesScope(name);
                if (scope == -1) {
                    scope = ScriptContext.ENGINE_SCOPE;
                }
                ctx.setAttribute(name, value, scope);
            }
        }
    };
    try {
        // then simply return that class
        if (!Script.class.isAssignableFrom(scriptClass)) {
            return scriptClass;
        } else {
            // it's a script
            Script scriptObject = InvokerHelper.createScript(scriptClass, binding);
            // save all current closures into global closures map
            Method[] methods = scriptClass.getMethods();
            for (Method m : methods) {
                String name = m.getName();
                globalClosures.put(name, new MethodClosure(scriptObject, name));
            }
            MetaClass oldMetaClass = scriptObject.getMetaClass();
            /*
                * We override the MetaClass of this script object so that we can
                * forward calls to global closures (of previous or future "eval" calls)
                * This gives the illusion of working on the same "global" scope.
                */
            scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) {

                @Override
                public Object invokeMethod(Object object, String name, Object args) {
                    if (args == null) {
                        return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY);
                    }
                    if (args instanceof Tuple) {
                        return invokeMethod(object, name, ((Tuple) args).toArray());
                    }
                    if (args instanceof Object[]) {
                        return invokeMethod(object, name, (Object[]) args);
                    } else {
                        return invokeMethod(object, name, new Object[] { args });
                    }
                }

                @Override
                public Object invokeMethod(Object object, String name, Object[] args) {
                    try {
                        return super.invokeMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, ctx);
                    }
                }

                @Override
                public Object invokeStaticMethod(Object object, String name, Object[] args) {
                    try {
                        return super.invokeStaticMethod(object, name, args);
                    } catch (MissingMethodException mme) {
                        return callGlobal(name, args, ctx);
                    }
                }
            });
            return scriptObject.run();
        }
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) MissingPropertyException(groovy.lang.MissingPropertyException) Method(java.lang.reflect.Method) MethodClosure(org.codehaus.groovy.runtime.MethodClosure) MissingPropertyException(groovy.lang.MissingPropertyException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) ScriptException(javax.script.ScriptException) MissingMethodException(groovy.lang.MissingMethodException) MetaClass(groovy.lang.MetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) DelegatingMetaClass(groovy.lang.DelegatingMetaClass) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) Tuple(groovy.lang.Tuple) PrintWriter(java.io.PrintWriter)

Example 17 with Script

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

the class XmlTemplateEngine method createTemplate.

public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException {
    Node root;
    try {
        root = xmlParser.parse(reader);
    } catch (SAXException e) {
        throw new RuntimeException("Parsing XML source failed.", e);
    }
    if (root == null) {
        throw new IOException("Parsing XML source failed: root node is null.");
    }
    StringWriter writer = new StringWriter(1024);
    writer.write("/* Generated by XmlTemplateEngine */\n");
    new GspPrinter(new PrintWriter(writer), indentation).print(root);
    Script script;
    try {
        script = groovyShell.parse(writer.toString(), "XmlTemplateScript" + counter++ + ".groovy");
    } catch (Exception e) {
        throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
    }
    return new XmlTemplate(script);
}
Also used : Script(groovy.lang.Script) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) StringWriter(java.io.StringWriter) Node(groovy.util.Node) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) IOException(java.io.IOException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SAXException(org.xml.sax.SAXException) PrintWriter(java.io.PrintWriter)

Example 18 with Script

use of groovy.lang.Script in project intellij-community by JetBrains.

the class ScriptSupport method checkValidScript.

public static String checkValidScript(String scriptText) {
    try {
        final File scriptFile = new File(scriptText);
        final GroovyShell shell = new GroovyShell();
        final Script script = scriptFile.exists() ? shell.parse(scriptFile) : shell.parse(scriptText);
        return null;
    } catch (IOException e) {
        return e.getMessage();
    } catch (MultipleCompilationErrorsException e) {
        final ErrorCollector errorCollector = e.getErrorCollector();
        final List<Message> errors = errorCollector.getErrors();
        for (Message error : errors) {
            if (error instanceof SyntaxErrorMessage) {
                final SyntaxErrorMessage errorMessage = (SyntaxErrorMessage) error;
                final SyntaxException cause = errorMessage.getCause();
                return cause.getMessage();
            }
        }
        return e.getMessage();
    } catch (CompilationFailedException ex) {
        return ex.getLocalizedMessage();
    }
}
Also used : Script(groovy.lang.Script) Message(org.codehaus.groovy.control.messages.Message) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ErrorCollector(org.codehaus.groovy.control.ErrorCollector) ArrayList(java.util.ArrayList) List(java.util.List) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) MultipleCompilationErrorsException(org.codehaus.groovy.control.MultipleCompilationErrorsException) File(java.io.File) GroovyShell(groovy.lang.GroovyShell)

Example 19 with Script

use of groovy.lang.Script in project sulky by huxi.

the class GroovyInstanceTest method broken.

@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
@Test
public void broken() throws IOException, InterruptedException {
    JUnitTools.copyResourceToFile("/Foo.groovy", fooFile, System.currentTimeMillis() - 2 * ONE_MINUTE);
    GroovyInstance instance = new GroovyInstance();
    instance.setGroovyFileName(fooFile.getAbsolutePath());
    instance.setRefreshInterval(1);
    Class instanceClass = instance.getInstanceClass();
    assertNotNull(instanceClass);
    assertEquals("Foo", instanceClass.getName());
    Object object = instance.getInstance();
    assertNotNull(object);
    assertTrue(object instanceof Script);
    Script script = (Script) object;
    String result = (String) script.run();
    assertEquals("Foo", result);
    JUnitTools.copyResourceToFile("/Broken.b0rken", fooFile, System.currentTimeMillis() - ONE_MINUTE);
    Thread.sleep(100);
    assertNull(instance.getInstanceClass());
    assertNull(instance.getInstance());
    // error should be logged only once...
    Thread.sleep(10);
    assertNull(instance.getInstanceClass());
    assertNull(instance.getInstance());
    Thread.sleep(10);
    assertNull(instance.getInstanceClass());
    assertNull(instance.getInstance());
    Thread.sleep(10);
    assertNotNull(instance.getErrorCause());
    assertNotNull(instance.getErrorMessage());
    JUnitTools.copyResourceToFile("/Bar.groovy", fooFile, System.currentTimeMillis());
    object = instance.getInstance();
    assertTrue(object instanceof Script);
    script = (Script) object;
    result = (String) script.run();
    assertEquals("Bar", result);
    assertNull(instance.getErrorCause());
    assertNull(instance.getErrorMessage());
}
Also used : Script(groovy.lang.Script) Test(org.junit.Test)

Example 20 with Script

use of groovy.lang.Script in project sulky by huxi.

the class GroovyInstanceTest method normal.

@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
@Test
public void normal() throws IOException {
    JUnitTools.copyResourceToFile("/Foo.groovy", fooFile, System.currentTimeMillis() - ONE_MINUTE);
    GroovyInstance instance = new GroovyInstance();
    instance.setGroovyFileName(fooFile.getAbsolutePath());
    Class instanceClass = instance.getInstanceClass();
    assertNotNull(instanceClass);
    assertEquals("Foo", instanceClass.getName());
    Object object = instance.getInstance();
    assertNotNull(object);
    assertTrue(object instanceof Script);
    Script script = (Script) object;
    String result = (String) script.run();
    assertEquals("Foo", result);
    assertNull(instance.getErrorCause());
    assertNull(instance.getErrorMessage());
    Object newObject = instance.getNewInstance();
    assertNotNull(object);
    assertTrue(newObject instanceof Script);
    Script newScript = (Script) newObject;
    String newResult = (String) newScript.run();
    assertEquals("Foo", newResult);
    assertNotSame(newScript, script);
    assertNotSame(instance.getNewInstance(), newScript);
    assertSame(instance.getInstance(), script);
    assertSame(script, instance.getInstanceAs(Script.class));
    assertNotSame(script, instance.getNewInstanceAs(Script.class));
    newScript = instance.getNewInstanceAs(Script.class);
    newResult = (String) newScript.run();
    assertEquals("Foo", newResult);
    assertNull(instance.getInstanceAs(Comparable.class));
    assertNull(instance.getNewInstanceAs(Comparable.class));
}
Also used : Script(groovy.lang.Script) Test(org.junit.Test)

Aggregations

Script (groovy.lang.Script)42 Binding (groovy.lang.Binding)21 IOException (java.io.IOException)12 GroovyShell (groovy.lang.GroovyShell)10 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)9 MissingMethodException (groovy.lang.MissingMethodException)6 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)5 PrintWriter (java.io.PrintWriter)5 Closure (groovy.lang.Closure)4 GroovyClassLoader (groovy.lang.GroovyClassLoader)4 MetaClass (groovy.lang.MetaClass)4 MissingPropertyException (groovy.lang.MissingPropertyException)4 File (java.io.File)4 UrlMapping (grails.web.mapping.UrlMapping)3 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)3 Tuple (groovy.lang.Tuple)3 Method (java.lang.reflect.Method)3 List (java.util.List)3 CompiledScript (javax.script.CompiledScript)3 ScriptException (javax.script.ScriptException)3