use of groovy.lang.Closure in project groovy by apache.
the class CachedSAMClass method coerceToSAM.
/* Should we make the following method private? */
@SuppressWarnings("unchecked")
public static Object coerceToSAM(Closure argument, Method method, Class clazz, boolean isInterface) {
if (argument != null && clazz.isAssignableFrom(argument.getClass())) {
return argument;
}
if (isInterface) {
if (Traits.isTrait(clazz)) {
Map<String, Closure> impl = Collections.singletonMap(method.getName(), argument);
return ProxyGenerator.INSTANCE.instantiateAggregate(impl, Collections.singletonList(clazz));
}
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new ConvertedClosure(argument));
} else {
Map<String, Object> m = new HashMap<String, Object>();
m.put(method.getName(), argument);
return ProxyGenerator.INSTANCE.instantiateAggregateFromBaseClass(m, clazz);
}
}
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 —
* 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
*/
@Override
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<String, Object> subMap = new LinkedHashMap<>();
subMap.putAll(asMap(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>());
}
}
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.
*/
@Override
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();
}
}
}
use of groovy.lang.Closure in project groovy by apache.
the class Node method build.
public void build(final GroovyObject builder, final Map namespaceMap, final Map<String, String> namespaceTagHints) {
if (this.replacementNodeStack.empty()) {
final Closure rest = new Closure(null) {
public Object doCall(final Object o) {
buildChildren(builder, namespaceMap, namespaceTagHints);
return null;
}
};
if (this.namespaceURI.length() == 0 && this.attributeNamespaces.isEmpty()) {
builder.invokeMethod(this.name, new Object[] { this.attributes, rest });
} else {
final List newTags = new LinkedList();
builder.getProperty("mkp");
final List namespaces = (List) builder.invokeMethod("getNamespaces", new Object[] {});
final Map current = (Map) namespaces.get(0);
final Map pending = (Map) namespaces.get(1);
if (this.attributeNamespaces.isEmpty()) {
builder.getProperty(getTagFor(this.namespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder));
builder.invokeMethod(this.name, new Object[] { this.attributes, rest });
} else {
final Map attributesWithNamespaces = new HashMap(this.attributes);
for (Object key : this.attributes.keySet()) {
final Object attributeNamespaceURI = this.attributeNamespaces.get(key);
if (attributeNamespaceURI != null) {
attributesWithNamespaces.put(getTagFor(attributeNamespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder) + "$" + key, attributesWithNamespaces.remove(key));
}
}
builder.getProperty(getTagFor(this.namespaceURI, current, pending, namespaceMap, namespaceTagHints, newTags, builder));
builder.invokeMethod(this.name, new Object[] { attributesWithNamespaces, rest });
}
// remove the new tags we had to define for this element
if (!newTags.isEmpty()) {
final Iterator iter = newTags.iterator();
do {
pending.remove(iter.next());
} while (iter.hasNext());
}
}
} else {
((ReplacementNode) this.replacementNodeStack.peek()).build(builder, namespaceMap, namespaceTagHints);
}
}
use of groovy.lang.Closure in project groovy by apache.
the class GPathResult method setProperty.
/**
* Replaces the specified property of this GPathResult with a new value.
*
* @param property the property of this GPathResult to replace
* @param newValue the new value of the property
*/
@Override
public void setProperty(final String property, final Object newValue) {
if (property.startsWith("@")) {
if (newValue instanceof String || newValue instanceof GString) {
for (Object o : this) {
final NodeChild child = (NodeChild) o;
child.attributes().put(property.substring(1), newValue);
}
}
} else {
final GPathResult result = new NodeChildren(this, property, this.namespaceTagHints);
if (newValue instanceof Map) {
for (Object o : ((Map) newValue).entrySet()) {
final Map.Entry entry = (Map.Entry) o;
result.setProperty("@" + entry.getKey(), entry.getValue());
}
} else {
if (newValue instanceof Closure) {
result.replaceNode((Closure) newValue);
} else {
result.replaceBody(newValue);
}
}
}
}
Aggregations