1 28 29 package com.caucho.xsl.fun; 30 31 import com.caucho.xpath.Expr; 32 import com.caucho.xpath.ExprEnvironment; 33 import com.caucho.xpath.XPathException; 34 import com.caucho.xpath.XPathFun; 35 import com.caucho.xpath.pattern.AbstractPattern; 36 37 import org.w3c.dom.Node ; 38 import org.w3c.dom.NodeList ; 39 40 import java.util.ArrayList ; 41 import java.util.HashMap ; 42 import java.util.Iterator ; 43 44 47 public class KeyFun extends XPathFun { 48 private HashMap <String ,Key> _keys; 49 50 public KeyFun() 51 { 52 _keys = new HashMap <String ,Key>(); 53 } 54 55 62 public void add(String name, AbstractPattern match, Expr use) 63 { 64 _keys.put(name, new Key(match, use)); 65 } 66 67 public HashMap <String ,Key> getKeys() 68 { 69 return _keys; 70 } 71 72 78 public Object eval(Node node, ExprEnvironment env, 79 AbstractPattern pattern, ArrayList args) 80 throws XPathException 81 { 82 if (args.size() < 2) 83 return null; 84 85 String name = Expr.toString(args.get(0)); 86 Key key = _keys.get(name); 87 Object value = args.get(1); 88 89 if (key == null) 90 return null; 91 92 if (value == null) 93 return null; 94 95 ArrayList nodes = new ArrayList (); 96 if (value instanceof NodeList ) { 97 NodeList list = (NodeList ) value; 98 for (int i = 0; i < list.getLength(); i++) 99 key(node, env, key._match, key._use, Expr.toString(list.item(i)), nodes); 100 } 101 else if (value instanceof ArrayList ) { 102 ArrayList list = (ArrayList ) value; 103 for (int i = 0; i < list.size(); i++) 104 key(node, env, key._match, key._use, Expr.toString(list.get(i)), nodes); 105 } 106 else if (value instanceof Iterator ) { 107 Iterator iter = (Iterator ) value; 108 while (iter.hasNext()) 109 key(node, env, key._match, key._use, Expr.toString(iter.next()), nodes); 110 } 111 else 112 key(node, env, key._match, key._use, Expr.toString(value), nodes); 113 114 return nodes; 115 } 116 117 private void key(Node node, ExprEnvironment env, 118 AbstractPattern match, Expr use, String value, 119 ArrayList nodes) 120 throws XPathException 121 { 122 Iterator iter = match.select(node, env); 123 while (iter.hasNext()) { 124 Node subnode = (Node ) iter.next(); 125 String nodeValue = use.evalString(subnode, env); 126 127 if (value.equals(nodeValue)) 128 nodes.add(subnode); 129 } 130 } 131 132 public static class Key { 133 AbstractPattern _match; 134 Expr _use; 135 136 Key(AbstractPattern match, Expr use) 137 { 138 _match = match; 139 _use = use; 140 } 141 142 public AbstractPattern getMatch() 143 { 144 return _match; 145 } 146 147 public Expr getUse() 148 { 149 return _use; 150 } 151 } 152 } 153 | Popular Tags |