Search in sources :

Example 6 with MissingMethodException

use of groovy.lang.MissingMethodException in project hudson-2.x by hudson.

the class BeanBuilder method methodMissing.

/**
	 * This method is invoked by Groovy when a method that's not defined in Java is invoked.
     * We use that as a syntax for bean definition. 
	 */
public Object methodMissing(String name, Object arg) {
    Object[] args = (Object[]) arg;
    if (args.length == 0)
        throw new MissingMethodException(name, getClass(), args);
    if (args[0] instanceof Closure) {
        // abstract bean definition
        return invokeBeanDefiningMethod(name, args);
    } else if (args[0] instanceof Class || args[0] instanceof RuntimeBeanReference || args[0] instanceof Map) {
        return invokeBeanDefiningMethod(name, args);
    } else if (args.length > 1 && args[args.length - 1] instanceof Closure) {
        return invokeBeanDefiningMethod(name, args);
    }
    WebApplicationContext ctx = springConfig.getUnrefreshedApplicationContext();
    MetaClass mc = DefaultGroovyMethods.getMetaClass(ctx);
    if (!mc.respondsTo(ctx, name, args).isEmpty()) {
        return mc.invokeMethod(ctx, name, args);
    }
    return this;
}
Also used : MissingMethodException(groovy.lang.MissingMethodException) Closure(groovy.lang.Closure) MetaClass(groovy.lang.MetaClass) GroovyObject(groovy.lang.GroovyObject) MetaClass(groovy.lang.MetaClass) RuntimeBeanReference(org.springframework.beans.factory.config.RuntimeBeanReference) HashMap(java.util.HashMap) Map(java.util.Map) ManagedMap(org.springframework.beans.factory.support.ManagedMap) WebApplicationContext(org.springframework.web.context.WebApplicationContext)

Example 7 with MissingMethodException

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

the class ConstrainedPropertyBuilder method createNode.

@SuppressWarnings("rawtypes")
@Override
protected Object createNode(Object name, Map attributes) {
    try {
        String property = (String) name;
        ConstrainedProperty cp;
        if (constrainedProperties.containsKey(property)) {
            cp = (ConstrainedProperty) constrainedProperties.get(property);
        } else {
            Class<?> propertyType = classPropertyFetcher.getPropertyType(property, true);
            if (propertyType == null) {
                throw new MissingMethodException(property, targetClass, new Object[] { attributes }, true);
            }
            cp = new ConstrainedProperty(targetClass, property, propertyType);
            cp.setOrder(order++);
            constrainedProperties.put(property, cp);
        }
        if (cp.getPropertyType() == null) {
            if (!IMPORT_FROM_CONSTRAINT.equals(name)) {
                GrailsUtil.warn("Property [" + cp.getPropertyName() + "] not found in domain class " + targetClass.getName() + "; cannot apply constraints: " + attributes);
            }
            return cp;
        }
        for (Object o : attributes.keySet()) {
            String constraintName = (String) o;
            final Object value = attributes.get(constraintName);
            if (SHARED_CONSTRAINT.equals(constraintName)) {
                if (value != null) {
                    sharedConstraints.put(property, value.toString());
                }
                continue;
            }
            if (cp.supportsContraint(constraintName)) {
                cp.applyConstraint(constraintName, value);
            } else {
                if (ConstrainedProperty.hasRegisteredConstraint(constraintName)) {
                    // constraint is registered but doesn't support this property's type
                    GrailsUtil.warn("Property [" + cp.getPropertyName() + "] of domain class " + targetClass.getName() + " has type [" + cp.getPropertyType().getName() + "] and doesn't support constraint [" + constraintName + "]. This constraint will not be checked during validation.");
                } else {
                    // in the case where the constraint is not supported we still retain meta data
                    // about the constraint in case its needed for other things
                    cp.addMetaConstraint(constraintName, value);
                }
            }
        }
        return cp;
    } catch (InvalidPropertyException ipe) {
        throw new MissingMethodException((String) name, targetClass, new Object[] { attributes });
    }
}
Also used : MissingMethodException(groovy.lang.MissingMethodException) InvalidPropertyException(org.springframework.beans.InvalidPropertyException) ConstrainedProperty(grails.validation.ConstrainedProperty)

Example 8 with MissingMethodException

use of groovy.lang.MissingMethodException in project groovy-core by groovy.

the class GroovyScriptEngineImpl method eval.

// package-privates
Object eval(Class scriptClass, final ScriptContext ctx) throws ScriptException {
    // Only initialize once.
    if (null == ctx.getAttribute("context", ScriptContext.ENGINE_SCOPE)) {
        // add context to bindings
        ctx.setAttribute("context", ctx, ScriptContext.ENGINE_SCOPE);
        // direct output to ctx.getWriter
        // If we're wrapping with a PrintWriter here,
        // enable autoFlush because otherwise it might not get done!
        final Writer writer = ctx.getWriter();
        ctx.setAttribute("out", (writer instanceof PrintWriter) ? writer : new PrintWriter(writer, true), ScriptContext.ENGINE_SCOPE);
    // Not going to do this after all (at least for now).
    // Scripts can use context.{reader, writer, errorWriter}.
    // That is a modern version of System.{in, out, err} or Console.{reader, writer}().
    //
    //            // New I/O names consistent with ScriptContext and java.io.Console.
    //
    //            ctx.setAttribute("writer", writer, ScriptContext.ENGINE_SCOPE);
    //
    //            // Direct errors to ctx.getErrorWriter
    //            final Writer errorWriter = ctx.getErrorWriter();
    //            ctx.setAttribute("errorWriter", (errorWriter instanceof PrintWriter) ?
    //                                    errorWriter :
    //                                    new PrintWriter(errorWriter),
    //                                    ScriptContext.ENGINE_SCOPE);
    //
    //            // Get input from ctx.getReader
    //            // We don't wrap with BufferedReader here because we expect that if
    //            // the host wants that they do it.  Either way Groovy scripts will
    //            // always have readLine because the GDK supplies it for Reader.
    //            ctx.setAttribute("reader", ctx.getReader(), ScriptContext.ENGINE_SCOPE);
    }
    // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for differents groovy script
    if (ctx.getWriter() != null) {
        ctx.setAttribute("out", new PrintWriter(ctx.getWriter(), true), ScriptContext.ENGINE_SCOPE);
    }
    /*
         * 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);
                }
            }
            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);
    } finally {
        // Fix for GROOVY-3669: Can't use several times the same JSR-223 ScriptContext for different groovy script
        // Groovy's scripting engine implementation adds those two variables in the binding
        // but should clean up afterwards
        ctx.removeAttribute("context", ScriptContext.ENGINE_SCOPE);
        ctx.removeAttribute("out", ScriptContext.ENGINE_SCOPE);
    }
}
Also used : Binding(groovy.lang.Binding) Script(groovy.lang.Script) CompiledScript(javax.script.CompiledScript) MissingPropertyException(groovy.lang.MissingPropertyException) String(java.lang.String) 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) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) 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 9 with MissingMethodException

use of groovy.lang.MissingMethodException in project groovy-core by groovy.

the class BuilderSupport method doInvokeMethod.

protected Object doInvokeMethod(String methodName, Object name, Object args) {
    Object node = null;
    Closure closure = null;
    List list = InvokerHelper.asList(args);
    switch(list.size()) {
        case 0:
            node = proxyBuilder.createNode(name);
            break;
        case 1:
            {
                Object object = list.get(0);
                if (object instanceof Map) {
                    node = proxyBuilder.createNode(name, (Map) object);
                } else if (object instanceof Closure) {
                    closure = (Closure) object;
                    node = proxyBuilder.createNode(name);
                } else {
                    node = proxyBuilder.createNode(name, object);
                }
            }
            break;
        case 2:
            {
                Object object1 = list.get(0);
                Object object2 = list.get(1);
                if (object1 instanceof Map) {
                    if (object2 instanceof Closure) {
                        closure = (Closure) object2;
                        node = proxyBuilder.createNode(name, (Map) object1);
                    } else {
                        node = proxyBuilder.createNode(name, (Map) object1, object2);
                    }
                } else {
                    if (object2 instanceof Closure) {
                        closure = (Closure) object2;
                        node = proxyBuilder.createNode(name, object1);
                    } else if (object2 instanceof Map) {
                        node = proxyBuilder.createNode(name, (Map) object2, object1);
                    } else {
                        throw new MissingMethodException(name.toString(), getClass(), list.toArray(), false);
                    }
                }
            }
            break;
        case 3:
            {
                Object arg0 = list.get(0);
                Object arg1 = list.get(1);
                Object arg2 = list.get(2);
                if (arg0 instanceof Map && arg2 instanceof Closure) {
                    closure = (Closure) arg2;
                    node = proxyBuilder.createNode(name, (Map) arg0, arg1);
                } else if (arg1 instanceof Map && arg2 instanceof Closure) {
                    closure = (Closure) arg2;
                    node = proxyBuilder.createNode(name, (Map) arg1, arg0);
                } else {
                    throw new MissingMethodException(name.toString(), getClass(), list.toArray(), false);
                }
            }
            break;
        default:
            {
                throw new MissingMethodException(name.toString(), getClass(), list.toArray(), false);
            }
    }
    if (current != null) {
        proxyBuilder.setParent(current, node);
    }
    if (closure != null) {
        // push new node on stack
        Object oldCurrent = getCurrent();
        setCurrent(node);
        // let's register the builder as the delegate
        setClosureDelegate(closure, node);
        closure.call();
        setCurrent(oldCurrent);
    }
    proxyBuilder.nodeCompleted(current, node);
    return proxyBuilder.postNodeCompletion(current, node);
}
Also used : MissingMethodException(groovy.lang.MissingMethodException) Closure(groovy.lang.Closure) List(java.util.List) Map(java.util.Map)

Example 10 with MissingMethodException

use of groovy.lang.MissingMethodException in project gradle by gradle.

the class ExtensibleDynamicObjectTest method canCallGroovyDynamicMethods.

@Test
public void canCallGroovyDynamicMethods() {
    DynamicGroovyBean bean = new DynamicGroovyBean();
    DynamicObject object = new ExtensibleDynamicObject(bean, DynamicGroovyBean.class, ThreadGlobalInstantiator.getOrCreate());
    Integer doubled = (Integer) object.invokeMethod("bar", 1);
    assertThat(doubled, equalTo(2));
    try {
        object.invokeMethod("xxx", 1, 2, 3);
        fail();
    } catch (MissingMethodException e) {
        assertThat(e.getMessage(), equalTo("Could not find method xxx() for arguments [1, 2, 3] on object of type " + DynamicGroovyBean.class.getName() + "."));
    }
}
Also used : MissingMethodException(groovy.lang.MissingMethodException) DynamicObject(org.gradle.internal.metaobject.DynamicObject) BeanDynamicObject(org.gradle.internal.metaobject.BeanDynamicObject) Test(org.junit.Test)

Aggregations

MissingMethodException (groovy.lang.MissingMethodException)16 Script (groovy.lang.Script)5 IOException (java.io.IOException)5 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)5 Closure (groovy.lang.Closure)4 MetaClass (groovy.lang.MetaClass)4 List (java.util.List)4 MethodClosure (org.codehaus.groovy.runtime.MethodClosure)4 Binding (groovy.lang.Binding)3 DelegatingMetaClass (groovy.lang.DelegatingMetaClass)3 GroovyObject (groovy.lang.GroovyObject)3 MissingPropertyException (groovy.lang.MissingPropertyException)3 Tuple (groovy.lang.Tuple)3 PrintWriter (java.io.PrintWriter)3 Method (java.lang.reflect.Method)3 Map (java.util.Map)3 CompiledScript (javax.script.CompiledScript)3 ScriptException (javax.script.ScriptException)3 Writer (java.io.Writer)2 ArrayList (java.util.ArrayList)2