1 16 package scriptella.driver.xpath; 17 18 import org.w3c.dom.Document ; 19 import org.w3c.dom.Element ; 20 import org.w3c.dom.Node ; 21 import org.w3c.dom.NodeList ; 22 import scriptella.expression.PropertiesSubstitutor; 23 import scriptella.spi.AbstractConnection; 24 import scriptella.spi.ParametersCallback; 25 import scriptella.spi.QueryCallback; 26 import scriptella.spi.Resource; 27 import scriptella.util.IOUtils; 28 import scriptella.util.StringUtils; 29 30 import javax.xml.xpath.XPathConstants ; 31 import javax.xml.xpath.XPathExpression ; 32 import javax.xml.xpath.XPathExpressionException ; 33 import java.io.IOException ; 34 35 41 public class XPathQueryExecutor implements ParametersCallback { 42 private Node node; 43 private PropertiesSubstitutor substitutor = new PropertiesSubstitutor(); 44 private Document document; 45 private String expressionStr; 46 private XPathExpressionCompiler compiler; 47 private AbstractConnection.StatementCounter counter; 48 49 56 public XPathQueryExecutor(Document document, Resource xpathResource, XPathExpressionCompiler compiler, AbstractConnection.StatementCounter counter) { 57 this.document = document; 58 this.compiler = compiler; 59 this.counter = counter; 60 try { 61 expressionStr = IOUtils.toString(xpathResource.open()); 62 } catch (IOException e) { 63 throw new XPathProviderException("Unable to read XPath query content"); 64 } 65 } 66 67 73 public void execute(final QueryCallback queryCallback, final ParametersCallback parentParameters) { 74 try { 75 substitutor.setParameters(parentParameters); 76 XPathExpression xpathExpression = compiler.compile(substitutor.substitute(expressionStr)); 77 NodeList nList = (NodeList ) xpathExpression.evaluate(document, XPathConstants.NODESET); 78 counter.statements++; 79 int n = nList.getLength(); 80 for (int i = 0; i < n; i++) { 81 node = nList.item(i); 82 queryCallback.processRow(this); 83 } 84 } catch (XPathExpressionException e) { 85 throw new XPathProviderException("Failed to evaluate XPath query", e); 86 } finally { 87 substitutor.setParameters(null); 88 } 89 } 90 91 public Object getParameter(final String name) { 92 Object result = null; 93 95 if (node instanceof Element ) { Node item = node.getAttributes().getNamedItem(name); 99 result = item == null ? null : StringUtils.nullsafeTrim(item.getNodeValue()); } 101 if (result == null && name.equals(node.getNodeName())) { 103 result = StringUtils.nullsafeTrim(node.getTextContent()); } 105 if (result == null && node instanceof Element ) { 107 Element element = (Element ) node; 108 NodeList list = element.getElementsByTagName(name); 109 int n = list.getLength(); 110 if (n > 0) { 113 String [] r = new String [n]; 114 for (int i = 0; i < n; i++) { 115 r[i] = StringUtils.nullsafeTrim(list.item(i).getTextContent()); 116 } 117 result = r.length > 1 ? r : r[0]; 118 } 119 } 120 return result == null ? substitutor.getParameters().getParameter(name) : result; 122 } 123 } 124 | Popular Tags |