1 16 17 package org.apache.commons.jexl.parser; 18 19 import org.apache.commons.jexl.JexlContext; 20 import org.apache.commons.jexl.util.Coercion; 21 import org.apache.commons.jexl.util.Introspector; 22 import org.apache.commons.jexl.util.introspection.Info; 23 import org.apache.commons.jexl.util.introspection.VelPropertyGet; 24 25 import java.util.List ; 26 import java.util.Map ; 27 import java.lang.reflect.Array ; 28 29 37 public class ASTArrayAccess extends SimpleNode { 38 39 private static final Info DUMMY = new Info("", 1, 1); 40 41 46 public ASTArrayAccess(int id) { 47 super(id); 48 } 49 50 56 public ASTArrayAccess(Parser p, int id) { 57 super(p, id); 58 } 59 60 61 public Object jjtAccept(ParserVisitor visitor, Object data) { 62 return visitor.visit(this, data); 63 } 64 65 76 public Object execute(Object obj, JexlContext jc) throws Exception { 77 ASTIdentifier base = (ASTIdentifier) jjtGetChild(0); 78 79 Object result = base.execute(obj, jc); 80 81 84 for (int i = 1; i < jjtGetNumChildren(); i++) { 85 Object loc = ((SimpleNode) jjtGetChild(i)).value(jc); 86 87 if (loc == null) { 88 return null; 89 } 90 91 result = evaluateExpr(result, loc); 92 } 93 94 return result; 95 } 96 97 98 public Object value(JexlContext jc) throws Exception { 99 102 103 ASTIdentifier base = (ASTIdentifier) jjtGetChild(0); 104 105 Object o = base.value(jc); 106 107 110 for (int i = 1; i < jjtGetNumChildren(); i++) { 111 Object loc = ((SimpleNode) jjtGetChild(i)).value(jc); 112 113 if (loc == null) { 114 return null; 115 } 116 117 o = evaluateExpr(o, loc); 118 } 119 120 return o; 121 } 122 123 138 public static Object evaluateExpr(Object o, Object loc) throws Exception { 139 142 143 if (o == null) { 144 return null; 145 } 146 147 if (loc == null) { 148 return null; 149 } 150 151 if (o instanceof Map ) { 152 if (!((Map ) o).containsKey(loc)) { 153 return null; 154 } 155 156 return ((Map ) o).get(loc); 157 } else if (o instanceof List ) { 158 int idx = Coercion.coerceInteger(loc).intValue(); 159 160 try { 161 return ((List ) o).get(idx); 162 } catch (IndexOutOfBoundsException iobe) { 163 return null; 164 } 165 } else if (o.getClass().isArray()) { 166 int idx = Coercion.coerceInteger(loc).intValue(); 167 168 try { 169 return Array.get(o, idx); 170 } catch (ArrayIndexOutOfBoundsException aiobe) { 171 return null; 172 } 173 } else { 174 177 178 String s = loc.toString(); 179 180 VelPropertyGet vg = Introspector.getUberspect().getPropertyGet(o, s, DUMMY); 181 182 if (vg != null) { 183 return vg.invoke(o); 184 } 185 } 186 187 throw new Exception ("Unsupported object type for array [] accessor"); 188 } 189 190 195 public String getIdentifierString() { 196 return ((ASTIdentifier) jjtGetChild(0)).getIdentifierString(); 197 } 198 } 199 | Popular Tags |