Search in sources :

Example 6 with Script

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

the class SecurityTestSupport method executeScript.

protected void executeScript(Class scriptClass, Permission missingPermission) {
    try {
        Script script = InvokerHelper.createScript(scriptClass, new Binding());
        script.run();
    //InvokerHelper.runScript(scriptClass, null);
    } catch (AccessControlException ace) {
        if (missingPermission != null && missingPermission.implies(ace.getPermission())) {
            return;
        } else {
            fail(ace.toString());
        }
    }
    if (missingPermission != null) {
        fail("Should catch an AccessControlException");
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script)

Example 7 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 8 with Script

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

the class InvokerHelper method runScript.

public static Object runScript(Class scriptClass, String[] args) {
    Binding context = new Binding(args);
    Script script = createScript(scriptClass, context);
    return invokeMethod(script, "run", EMPTY_ARGS);
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script)

Example 9 with Script

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

the class GroovySnippetExecuter method execute.

@Override
public void execute(TestCodeSnippet snippet) throws Exception {
    CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(new CompilationCustomizer(CompilePhase.CONVERSION) {

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
            if (compileStatic) {
                classNode.addAnnotation(new AnnotationNode(new ClassNode(CompileStatic.class)));
            }
        }
    });
    ClassLoader classLoader = new URLClassLoader(new URL[] {}, getClass().getClassLoader());
    GroovyShell groovyShell = new GroovyShell(classLoader, new Binding(), config);
    List<String> importsAndSnippet = extractImports(snippet.getSnippet());
    String imports = importsAndSnippet.get(0);
    String snippetMinusImports = fixture.transform(importsAndSnippet.get(1));
    String fullSnippet = imports + fixture.pre() + snippetMinusImports + fixture.post();
    Script script;
    try {
        script = groovyShell.parse(fullSnippet, snippet.getClassName());
    } catch (MultipleCompilationErrorsException e) {
        Message error = e.getErrorCollector().getError(0);
        if (error instanceof SyntaxErrorMessage) {
            //noinspection ThrowableResultOfMethodCallIgnored
            System.out.println(snippet.getSnippet());
            throw new CompileException(e, ((SyntaxErrorMessage) error).getCause().getLine());
        } else {
            throw e;
        }
    }
    ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(groovyShell.getClassLoader());
        fixture.around(script::run);
    } finally {
        Thread.currentThread().setContextClassLoader(previousContextClassLoader);
    }
}
Also used : Binding(groovy.lang.Binding) ClassNode(org.codehaus.groovy.ast.ClassNode) 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) CompileStatic(groovy.transform.CompileStatic) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) GroovyShell(groovy.lang.GroovyShell) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) CompilationCustomizer(org.codehaus.groovy.control.customizers.CompilationCustomizer)

Example 10 with Script

use of groovy.lang.Script in project grails-core by grails.

the class DefaultUrlMappingEvaluatorTests method testRedirectMappings.

public void testRedirectMappings() throws Exception {
    GroovyShell shell = new GroovyShell();
    Binding binding = new Binding();
    Script script = shell.parse("mappings = {\n" + "\"/first\"(redirect:[controller: 'foo', action: 'bar'])\n" + "\"/second\"(redirect: '/bing/bang')\n" + "}");
    script.setBinding(binding);
    script.run();
    Closure closure = (Closure) binding.getVariable("mappings");
    List<UrlMapping> mappings = evaluator.evaluateMappings(closure);
    assertEquals(2, mappings.size());
    Object redirectInfo = mappings.get(0).getRedirectInfo();
    assertTrue(redirectInfo instanceof Map);
    Map redirectMap = (Map) redirectInfo;
    assertEquals(2, redirectMap.size());
    assertEquals("foo", redirectMap.get("controller"));
    assertEquals("bar", redirectMap.get("action"));
    assertEquals("/bing/bang", mappings.get(1).getRedirectInfo());
}
Also used : Binding(groovy.lang.Binding) UrlMapping(grails.web.mapping.UrlMapping) Script(groovy.lang.Script) Closure(groovy.lang.Closure) Map(java.util.Map) GroovyShell(groovy.lang.GroovyShell)

Aggregations

Script (groovy.lang.Script)37 Binding (groovy.lang.Binding)19 IOException (java.io.IOException)12 GroovyShell (groovy.lang.GroovyShell)10 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)8 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