1 15 package org.apache.hivemind.schema.rules; 16 17 import java.lang.reflect.Method ; 18 19 import org.apache.hivemind.ApplicationRuntimeException; 20 import org.apache.hivemind.Element; 21 import org.apache.hivemind.schema.SchemaProcessor; 22 import org.apache.hivemind.util.PropertyUtils; 23 24 31 public class AddToMapRule extends BaseRule 32 { 33 private String _methodName; 34 35 private String _keyAttribute; 36 37 public AddToMapRule(String keyAttribute) 38 { 39 this("put", keyAttribute); 40 } 41 42 public AddToMapRule(String methodName, String keyAttribute) 43 { 44 _methodName = methodName; 45 _keyAttribute = keyAttribute; 46 } 47 48 51 public void begin(SchemaProcessor processor, Element element) 52 { 53 Object parent = processor.peek(1); 54 Object child = processor.peek(); 55 56 Object [] parameters = new Object [2]; 58 parameters[0] = getKeyValue(child); 59 parameters[1] = child; 60 61 Class [] parameterTypes = new Class [2]; 62 parameterTypes[0] = getKeyType(child); 63 parameterTypes[1] = child.getClass(); 64 65 try 66 { 67 Method m = findMethod(parent, _methodName, parameterTypes); 68 69 m.invoke(parent, parameters); 70 } 71 catch (Exception ex) 72 { 73 throw new ApplicationRuntimeException(RulesMessages.errorInvokingMethod( 74 _methodName, 75 parent, 76 getLocation(), 77 ex), getLocation(), ex); 78 } 79 } 80 81 public String getMethodName() 82 { 83 return _methodName; 84 } 85 86 public void setMethodName(String string) 87 { 88 _methodName = string; 89 } 90 91 98 private Method findMethod(Object target, String name, Class [] parameterTypes) 99 throws NoSuchMethodException 100 { 101 Method [] methods = target.getClass().getMethods(); 102 103 for (int i = 0; i < methods.length; i++) 104 { 105 Method m = methods[i]; 106 Class [] actualParameterTypes = m.getParameterTypes(); 107 108 if (actualParameterTypes.length != parameterTypes.length) 109 continue; 110 111 if (!m.getName().equals(name)) 112 continue; 113 114 for (int j = 0; j < actualParameterTypes.length; j++) 115 { 116 Class actualParameterType = actualParameterTypes[j]; 117 Class expectedParameterType = parameterTypes[j]; 118 if ((expectedParameterType != null && actualParameterType.isAssignableFrom(expectedParameterType)) 119 || (expectedParameterType == null && !actualParameterType.isPrimitive())) 120 return m; 121 122 } 123 } 124 125 throw new NoSuchMethodException (name); 126 } 127 128 132 private Class getKeyType(Object child) 133 { 134 return PropertyUtils.getPropertyType(child, _keyAttribute); 135 } 136 137 141 private Object getKeyValue(Object child) 142 { 143 return PropertyUtils.read(child, _keyAttribute); 144 } 145 146 } 147 | Popular Tags |