`ClosureToMapPopulator.java`
`01 /* 02 * Copyright 2004-2012 the original author or authors. 03 * 04 * Licensed under the Apache License, Version 2.0 (the "License"); 05 * you may not use this file except in compliance with the License. 06 * You may obtain a copy of the License at 07 * 08 * http://www.apache.org/licenses/LICENSE-2.0 09 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package griffon.util; 17 18 import groovy.lang.Closure; 19 import groovy.lang.GroovyObjectSupport; 20 21 import java.util.Arrays; 22 import java.util.HashMap; 23 import java.util.Map; 24 25 /** 26 * A simple class that takes method invocations and property setters and populates 27 * the arguments of these into the supplied map ignoring null values. 28 * 29 * @author Graeme Rocher (Grails 1.2) 30 * @since 0.9.1 31 */ 32 @SuppressWarnings("unchecked") 33 public class ClosureToMapPopulator extends GroovyObjectSupport { 34 private Map map; 35 36 public ClosureToMapPopulator(Map theMap) { 37 map = theMap; 38 } 39 40 public ClosureToMapPopulator() { 41 this(new HashMap()); 42 } 43 44 public Map populate(Closure callable) { 45 callable.setDelegate(this); 46 callable.setResolveStrategy(Closure.DELEGATE_FIRST); 47 callable.call(); 48 return map; 49 } 50 51 @Override 52 public void setProperty(String name, Object o) { 53 if (o != null) { 54 map.put(name, o); 55 } 56 } 57 58 @Override 59 public Object invokeMethod(String name, Object o) { 60 if (o != null) { 61 if (o.getClass().isArray()) { 62 Object[] args = (Object[]) o; 63 if (args.length == 1) { 64 map.put(name, args[0]); 65 } else { 66 map.put(name, Arrays.asList(args)); 67 } 68 } else { 69 map.put(name, o); 70 } 71 } 72 return null; 73 } 74 }`