1 /* Copyright 2004-2005 the original author or authors. 2 * 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 package grails.util; 16 17 import groovy.lang.Closure; 18 import groovy.lang.GroovyObjectSupport; 19 20 import java.util.Arrays; 21 import java.util.HashMap; 22 import java.util.Map; 23 24 /** 25 * A simple class that takes method invocations and property setters and populates 26 * the arguments of these into the supplied map ignoring null values. 27 * 28 * @author Graeme Rocher 29 * @since 1.2 30 */ 31 @SuppressWarnings({"unchecked","rawtypes"}) 32 public class ClosureToMapPopulator extends GroovyObjectSupport { 33 34 private Map map; 35 ClosureToMapPopulator(Map theMap)36 public ClosureToMapPopulator(Map theMap) { 37 map = theMap; 38 } 39 ClosureToMapPopulator()40 public ClosureToMapPopulator() { 41 this(new HashMap()); 42 } 43 populate(Closure callable)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 setProperty(String name, Object o)52 public void setProperty(String name, Object o) { 53 if (o != null) { 54 map.put(name, o); 55 } 56 } 57 58 @Override invokeMethod(String name, Object o)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 } 66 else { 67 map.put(name, Arrays.asList(args)); 68 } 69 } 70 else { 71 map.put(name,o); 72 } 73 } 74 return null; 75 } 76 } 77