1 7 8 package org.dom4j.xpath; 9 10 import java.util.ArrayList ; 11 12 import org.dom4j.InvalidXPathException; 13 import org.dom4j.Node; 14 import org.dom4j.XPathException; 15 16 import org.jaxen.Context; 17 import org.jaxen.ContextSupport; 18 import org.jaxen.JaxenException; 19 import org.jaxen.SimpleNamespaceContext; 20 import org.jaxen.SimpleVariableContext; 21 import org.jaxen.VariableContext; 22 import org.jaxen.XPathFunctionContext; 23 import org.jaxen.dom4j.DocumentNavigator; 24 import org.jaxen.pattern.Pattern; 25 import org.jaxen.pattern.PatternParser; 26 import org.jaxen.saxpath.SAXPathException; 27 28 37 public class XPathPattern implements org.dom4j.rule.Pattern { 38 private String text; 39 40 private Pattern pattern; 41 42 private Context context; 43 44 public XPathPattern(Pattern pattern) { 45 this.pattern = pattern; 46 this.text = pattern.getText(); 47 this.context = new Context(getContextSupport()); 48 } 49 50 public XPathPattern(String text) { 51 this.text = text; 52 this.context = new Context(getContextSupport()); 53 54 try { 55 this.pattern = PatternParser.parse(text); 56 } catch (SAXPathException e) { 57 throw new InvalidXPathException(text, e.getMessage()); 58 } catch (Throwable t) { 59 throw new InvalidXPathException(text, t); 60 } 61 } 62 63 public boolean matches(Node node) { 64 try { 65 ArrayList list = new ArrayList (1); 66 list.add(node); 67 context.setNodeSet(list); 68 69 return pattern.matches(node, context); 70 } catch (JaxenException e) { 71 handleJaxenException(e); 72 73 return false; 74 } 75 } 76 77 public String getText() { 78 return text; 79 } 80 81 public double getPriority() { 82 return pattern.getPriority(); 83 } 84 85 public org.dom4j.rule.Pattern[] getUnionPatterns() { 86 Pattern[] patterns = pattern.getUnionPatterns(); 87 88 if (patterns != null) { 89 int size = patterns.length; 90 XPathPattern[] answer = new XPathPattern[size]; 91 92 for (int i = 0; i < size; i++) { 93 answer[i] = new XPathPattern(patterns[i]); 94 } 95 96 return answer; 97 } 98 99 return null; 100 } 101 102 public short getMatchType() { 103 return pattern.getMatchType(); 104 } 105 106 public String getMatchesNodeName() { 107 return pattern.getMatchesNodeName(); 108 } 109 110 public void setVariableContext(VariableContext variableContext) { 111 context.getContextSupport().setVariableContext(variableContext); 112 } 113 114 public String toString() { 115 return "[XPathPattern: text: " + text + " Pattern: " + pattern + "]"; 116 } 117 118 protected ContextSupport getContextSupport() { 119 return new ContextSupport(new SimpleNamespaceContext(), 120 XPathFunctionContext.getInstance(), 121 new SimpleVariableContext(), DocumentNavigator.getInstance()); 122 } 123 124 protected void handleJaxenException(JaxenException exception) 125 throws XPathException { 126 throw new XPathException(text, exception); 127 } 128 } 129 130 166 | Popular Tags |