Search in sources :

Example 11 with MethodClosure

use of org.codehaus.groovy.runtime.MethodClosure 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 12 with MethodClosure

use of org.codehaus.groovy.runtime.MethodClosure in project groovy by apache.

the class ServletBinding method lazyInit.

private void lazyInit() {
    if (initialized)
        return;
    initialized = true;
    HttpServletResponse response = (HttpServletResponse) super.getVariable("response");
    ServletOutput output = new ServletOutput(response);
    super.setVariable("out", output.getWriter());
    super.setVariable("sout", output.getOutputStream());
    MarkupBuilder builder = new MarkupBuilder(output.getWriter());
    builder.setExpandEmptyElements(true);
    super.setVariable("html", builder);
    try {
        // load using reflection to avoid needing a hard requirement on groovy-json for those not needing JSON support
        Class jsonBuilderClass = this.getClass().getClassLoader().loadClass("groovy.json.StreamingJsonBuilder");
        Constructor writerConstructor = getWriterConstructor(jsonBuilderClass);
        super.setVariable("json", writerConstructor.newInstance(output.getWriter()));
    } catch (Throwable t) {
        t.printStackTrace();
    }
    // bind forward method
    MethodClosure c = new MethodClosure(this, "forward");
    super.setVariable("forward", c);
    // bind include method
    c = new MethodClosure(this, "include");
    super.setVariable("include", c);
    // bind redirect method
    c = new MethodClosure(this, "redirect");
    super.setVariable("redirect", c);
}
Also used : Constructor(java.lang.reflect.Constructor) HttpServletResponse(javax.servlet.http.HttpServletResponse) MarkupBuilder(groovy.xml.MarkupBuilder) MethodClosure(org.codehaus.groovy.runtime.MethodClosure)

Example 13 with MethodClosure

use of org.codehaus.groovy.runtime.MethodClosure in project cucumber-jvm by cucumber.

the class HooksTest method only_allows_arguments_string_long_integer_closure.

@Test
public void only_allows_arguments_string_long_integer_closure() {
    try {
        Hooks.Before("TAG", 10L, 100, new MethodClosure(this, "dummyClosureCall"), 0.0);
        fail("CucumberException was not thrown");
    } catch (CucumberException e) {
        assertEquals("An argument of the type java.lang.Double found, Before only allows the argument types " + "String - Tag, Long - timeout, Integer - order, and Closure", e.getMessage());
    }
}
Also used : CucumberException(cucumber.runtime.CucumberException) MethodClosure(org.codehaus.groovy.runtime.MethodClosure) Test(org.junit.Test)

Example 14 with MethodClosure

use of org.codehaus.groovy.runtime.MethodClosure in project cucumber-jvm by cucumber.

the class GroovyBackendTest method should_build_world_by_calling_the_closure.

@Test
public void should_build_world_by_calling_the_closure() {
    backend.registerWorld(new MethodClosure(this, "worldClosureCall"));
    backend.buildWorld();
    GroovyWorld groovyWorld = backend.getGroovyWorld();
    assertEquals(1, groovyWorld.worldsCount());
}
Also used : MethodClosure(org.codehaus.groovy.runtime.MethodClosure) Test(org.junit.Test)

Example 15 with MethodClosure

use of org.codehaus.groovy.runtime.MethodClosure in project pact-jvm by DiUS.

the class MockMvcTarget method setupVerifier.

@Override
protected ProviderVerifier setupVerifier(Interaction interaction, ProviderInfo provider, ConsumerInfo consumer) {
    MvcProviderVerifier verifier = new MvcProviderVerifier();
    verifier.setDebugRequestResponse(printRequestResponse);
    setupReporters(verifier, provider.getName(), interaction.getDescription());
    verifier.setProjectClasspath(new MethodClosure(this, "getClassPathUrls"));
    verifier.initialiseReporters(provider);
    verifier.reportVerificationForConsumer(consumer, provider);
    if (interaction.getProviderState() != null) {
        verifier.reportStateForInteraction(interaction.getProviderState(), provider, consumer, true);
    }
    verifier.reportInteractionDescription(interaction);
    return verifier;
}
Also used : MvcProviderVerifier(au.com.dius.pact.provider.spring.MvcProviderVerifier) MethodClosure(org.codehaus.groovy.runtime.MethodClosure)

Aggregations

MethodClosure (org.codehaus.groovy.runtime.MethodClosure)28 IOException (java.io.IOException)5 CachedClass (org.codehaus.groovy.reflection.CachedClass)5 GeneratedClosure (org.codehaus.groovy.runtime.GeneratedClosure)4 Test (org.junit.Test)4 Binding (groovy.lang.Binding)3 Closure (groovy.lang.Closure)3 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)3 MetaClass (groovy.lang.MetaClass)3 MissingMethodException (groovy.lang.MissingMethodException)3 MissingPropertyException (groovy.lang.MissingPropertyException)3 Script (groovy.lang.Script)3 Tuple (groovy.lang.Tuple)3 PrintWriter (java.io.PrintWriter)3 Method (java.lang.reflect.Method)3 ArrayList (java.util.ArrayList)3 CompiledScript (javax.script.CompiledScript)3 ScriptException (javax.script.ScriptException)3 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)3 InvokerInvocationException (org.codehaus.groovy.runtime.InvokerInvocationException)3