Search in sources :

Example 6 with Closure

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

the class JsonBuilder method invokeMethod.

/**
     * A method call on the JSON builder instance will create a root object with only one key
     * whose name is the name of the method being called.
     * This method takes as arguments:
     * <ul>
     *     <li>a closure</li>
     *     <li>a map (ie. named arguments)</li>
     *     <li>a map and a closure</li>
     *     <li>or no argument at all</li>
     * </ul>
     * <p>
     * Example with a classical builder-style:
     * <pre><code class="groovyTestCase">
     * def json = new groovy.json.JsonBuilder()
     * def result = json.person {
     *      name "Guillaume"
     *      age 33
     * }
     *
     * assert result instanceof Map
     * assert json.toString() == '{"person":{"name":"Guillaume","age":33}}'
     * </code></pre>
     *
     * Or alternatively with a method call taking named arguments:
     * <pre><code class="groovyTestCase">
     * def json = new groovy.json.JsonBuilder()
     * json.person name: "Guillaume", age: 33
     *
     * assert json.toString() == '{"person":{"name":"Guillaume","age":33}}'
     * </code></pre>
     *
     * If you use named arguments and a closure as last argument,
     * the key/value pairs of the map (as named arguments)
     * and the key/value pairs represented in the closure
     * will be merged together &mdash;
     * the closure properties overriding the map key/values
     * in case the same key is used.
     * <pre><code class="groovyTestCase">
     * def json = new groovy.json.JsonBuilder()
     * json.person(name: "Guillaume", age: 33) { town "Paris" }
     *
     * assert json.toString() == '{"person":{"name":"Guillaume","age":33,"town":"Paris"}}'
     * </code></pre>
     *
     * The empty args call will create a key whose value will be an empty JSON object:
     * <pre><code class="groovyTestCase">
     * def json = new groovy.json.JsonBuilder()
     * json.person()
     *
     * assert json.toString() == '{"person":{}}'
     * </code></pre>
     *
     * @param name the single key
     * @param args the value associated with the key
     * @return a map with a single key
     */
public Object invokeMethod(String name, Object args) {
    if (args != null && Object[].class.isAssignableFrom(args.getClass())) {
        Object[] arr = (Object[]) args;
        if (arr.length == 0) {
            return setAndGetContent(name, new HashMap<String, Object>());
        } else if (arr.length == 1) {
            if (arr[0] instanceof Closure) {
                return setAndGetContent(name, JsonDelegate.cloneDelegateAndGetContent((Closure) arr[0]));
            } else if (arr[0] instanceof Map) {
                return setAndGetContent(name, arr[0]);
            }
        } else if (arr.length == 2) {
            final Object first = arr[0];
            final Object second = arr[1];
            if (second instanceof Closure) {
                final Closure closure = (Closure) second;
                if (first instanceof Map) {
                    Map subMap = new LinkedHashMap();
                    subMap.putAll((Map) first);
                    subMap.putAll(JsonDelegate.cloneDelegateAndGetContent(closure));
                    return setAndGetContent(name, subMap);
                } else if (first instanceof Iterable) {
                    List<Map<String, Object>> list = collectContentForEachEntry((Iterable) first, closure);
                    return setAndGetContent(name, list);
                } else if (first != null && first.getClass().isArray()) {
                    final Iterable coll = Arrays.asList((Object[]) first);
                    List<Map<String, Object>> list = collectContentForEachEntry(coll, closure);
                    return setAndGetContent(name, list);
                }
            }
        }
        throw new JsonException("Expected no arguments, a single map, a single closure, or a map and closure as arguments.");
    } else {
        return setAndGetContent(name, new HashMap<String, Object>());
    }
}
Also used : Closure(groovy.lang.Closure)

Example 7 with Closure

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

the class JmxEventListener method handleNotification.

/**
     * This is the implemented method for NotificationListener.  It is called by an event emitter to dispatch
     * JMX events to listeners.  Here it handles internal JmxBuilder events.
     *
     * @param notification the notification object passed to closure used to handle JmxBuilder events.
     * @param handback     - In this case, the handback is the closure to execute when the event is handled.
     */
public void handleNotification(Notification notification, Object handback) {
    Map event = (Map) handback;
    if (event != null) {
        Object del = event.get("managedObject");
        Object callback = event.get("callback");
        if (callback != null && callback instanceof Closure) {
            Closure closure = (Closure) callback;
            closure.setDelegate(del);
            if (closure.getMaximumNumberOfParameters() == 1)
                closure.call(buildOperationNotificationPacket(notification));
            else
                closure.call();
        }
    }
}
Also used : Closure(groovy.lang.Closure) Map(java.util.Map) HashMap(java.util.HashMap)

Example 8 with Closure

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

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);
        try {
            closure.call();
        } catch (Exception e) {
            throw new GroovyRuntimeException(e);
        }
        setCurrent(oldCurrent);
    }
    proxyBuilder.nodeCompleted(current, node);
    return proxyBuilder.postNodeCompletion(current, node);
}
Also used : MissingMethodException(groovy.lang.MissingMethodException) Closure(groovy.lang.Closure) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) List(java.util.List) Map(java.util.Map) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) MissingMethodException(groovy.lang.MissingMethodException)

Example 9 with Closure

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

the class Expando method hashCode.

/**
     * This allows hashCode to be overridden by a closure <i>field</i> method attached
     * to the expando object.
     *
     * @see java.lang.Object#hashCode()
     */
public int hashCode() {
    Object method = getProperties().get("hashCode");
    if (method != null && method instanceof Closure) {
        // invoke overridden hashCode closure method
        Closure closure = (Closure) method;
        closure.setDelegate(this);
        Integer ret = (Integer) closure.call();
        return ret.intValue();
    } else {
        return super.hashCode();
    }
}
Also used : Closure(groovy.lang.Closure)

Example 10 with Closure

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

the class AbstractTypeCheckingExtension method newScope.

public TypeCheckingScope newScope(Closure code) {
    TypeCheckingScope scope = newScope();
    Closure callback = code.rehydrate(scope, this, this);
    callback.call();
    return scope;
}
Also used : Closure(groovy.lang.Closure)

Aggregations

Closure (groovy.lang.Closure)211 Map (java.util.Map)40 GroovyObject (groovy.lang.GroovyObject)27 HashMap (java.util.HashMap)27 Binding (groovy.lang.Binding)21 ArrayList (java.util.ArrayList)21 List (java.util.List)19 GString (groovy.lang.GString)17 GroovyShell (groovy.lang.GroovyShell)13 MethodClosure (org.codehaus.groovy.runtime.MethodClosure)13 LinkedHashMap (java.util.LinkedHashMap)12 Test (org.junit.Test)12 File (java.io.File)10 LinkedList (java.util.LinkedList)10 FileType (groovy.io.FileType)8 FileVisitResult (groovy.io.FileVisitResult)8 MetaClass (groovy.lang.MetaClass)8 Collection (java.util.Collection)8 Script (groovy.lang.Script)7 IOException (java.io.IOException)7