KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > xerces > impl > xs > identity > XPathMatcher


1 /*
2  * Copyright 2001, 2002,2004,2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.xerces.impl.xs.identity;
18
19 import org.apache.xerces.impl.Constants;
20 import org.apache.xerces.impl.xpath.XPath;
21 import org.apache.xerces.util.IntStack;
22 import org.apache.xerces.xni.QName;
23 import org.apache.xerces.xni.XMLAttributes;
24 import org.apache.xerces.xs.AttributePSVI;
25 import org.apache.xerces.xs.ShortList;
26 import org.apache.xerces.xs.XSTypeDefinition;
27 import org.xml.sax.SAXException JavaDoc;
28
29
30 /**
31  * XPath matcher.
32  *
33  * @xerces.internal
34  *
35  * @author Andy Clark, IBM
36  *
37  * @version $Id: XPathMatcher.java,v 1.26 2005/05/09 21:03:33 ankitp Exp $
38  */

39 public class XPathMatcher {
40
41     //
42
// Constants
43
//
44

45     // debugging
46

47     /** Compile to true to debug everything. */
48     protected static final boolean DEBUG_ALL = false;
49
50     /** Compile to true to debug method callbacks. */
51     protected static final boolean DEBUG_METHODS = false || DEBUG_ALL;
52
53     /** Compile to true to debug important method callbacks. */
54     protected static final boolean DEBUG_METHODS2 = false || DEBUG_METHODS || DEBUG_ALL;
55
56     /** Compile to true to debug the <em>really</em> important methods. */
57     protected static final boolean DEBUG_METHODS3 = false || DEBUG_METHODS || DEBUG_ALL;
58
59     /** Compile to true to debug match. */
60     protected static final boolean DEBUG_MATCH = false || DEBUG_ALL;
61
62     /** Compile to true to debug step index stack. */
63     protected static final boolean DEBUG_STACK = false || DEBUG_ALL;
64
65     /** Don't touch this value unless you add more debug constants. */
66     protected static final boolean DEBUG_ANY = DEBUG_METHODS ||
67                                                DEBUG_METHODS2 ||
68                                                DEBUG_METHODS3 ||
69                                                DEBUG_MATCH ||
70                                                DEBUG_STACK;
71
72     // constants describing whether a match was made,
73
// and if so how.
74
// matched any way
75
protected static final int MATCHED = 1;
76     // matched on the attribute axis
77
protected static final int MATCHED_ATTRIBUTE = 3;
78     // matched on the descendant-or-self axixs
79
protected static final int MATCHED_DESCENDANT = 5;
80     // matched some previous (ancestor) node on the descendant-or-self-axis, but not this node
81
protected static final int MATCHED_DESCENDANT_PREVIOUS = 13;
82
83     //
84
// Data
85
//
86

87     /** XPath location path. */
88     private XPath.LocationPath[] fLocationPaths;
89
90     /** True if XPath has been matched. */
91     private int[] fMatched;
92
93     /** The matching string. */
94     protected Object JavaDoc fMatchedString;
95
96     /** Integer stack of step indexes. */
97     private IntStack[] fStepIndexes;
98
99     /** Current step. */
100     private int[] fCurrentStep;
101
102     /**
103      * No match depth. The value of this field will be zero while
104      * matching is successful for the given xpath expression.
105      */

106     private int [] fNoMatchDepth;
107     
108     final QName fQName = new QName();
109
110
111     //
112
// Constructors
113
//
114

115     /**
116      * Constructs an XPath matcher that implements a document fragment
117      * handler.
118      *
119      * @param xpath The xpath.
120      */

121     public XPathMatcher(XPath xpath) {
122         fLocationPaths = xpath.getLocationPaths();
123         fStepIndexes = new IntStack[fLocationPaths.length];
124         for(int i=0; i<fStepIndexes.length; i++) fStepIndexes[i] = new IntStack();
125         fCurrentStep = new int[fLocationPaths.length];
126         fNoMatchDepth = new int[fLocationPaths.length];
127         fMatched = new int[fLocationPaths.length];
128     } // <init>(XPath)
129

130     //
131
// Public methods
132
//
133

134     /**
135      * Returns value of first member of fMatched that
136      * is nonzero.
137      */

138     public boolean isMatched() {
139         // xpath has been matched if any one of the members of the union have matched.
140
for (int i=0; i < fLocationPaths.length; i++)
141             if (((fMatched[i] & MATCHED) == MATCHED)
142                     && ((fMatched[i] & MATCHED_DESCENDANT_PREVIOUS) != MATCHED_DESCENDANT_PREVIOUS)
143                     && ((fNoMatchDepth[i] == 0)
144                     || ((fMatched[i] & MATCHED_DESCENDANT) == MATCHED_DESCENDANT)))
145                 return true;
146
147         return false;
148     } // isMatched():int
149

150     //
151
// Protected methods
152
//
153

154     // a place-holder method; to be overridden by subclasses
155
// that care about matching element content.
156
protected void handleContent(XSTypeDefinition type, boolean nillable, Object JavaDoc value, short valueType, ShortList itemValueType) {
157     }
158
159     /**
160      * This method is called when the XPath handler matches the
161      * XPath expression. Subclasses can override this method to
162      * provide default handling upon a match.
163      */

164     protected void matched(Object JavaDoc actualValue, short valueType, ShortList itemValueType, boolean isNil) {
165         if (DEBUG_METHODS3) {
166             System.out.println(toString()+"#matched(\""+actualValue+"\")");
167         }
168     } // matched(String content, XSSimpleType val)
169

170     //
171
// ~XMLDocumentFragmentHandler methods
172
//
173

174     /**
175      * The start of the document fragment.
176      */

177     public void startDocumentFragment(){
178         if (DEBUG_METHODS) {
179             System.out.println(toString()+"#startDocumentFragment("+
180                                ")");
181         }
182
183         // reset state
184
fMatchedString = null;
185         for(int i = 0; i < fLocationPaths.length; i++) {
186             fStepIndexes[i].clear();
187             fCurrentStep[i] = 0;
188             fNoMatchDepth[i] = 0;
189             fMatched[i] = 0;
190         }
191
192
193     } // startDocumentFragment()
194

195     /**
196      * The start of an element. If the document specifies the start element
197      * by using an empty tag, then the startElement method will immediately
198      * be followed by the endElement method, with no intervening methods.
199      *
200      * @param element The name of the element.
201      * @param attributes The element attributes.
202      *
203      * @throws SAXException Thrown by handler to signal an error.
204      */

205     public void startElement(QName element, XMLAttributes attributes){
206         if (DEBUG_METHODS2) {
207             System.out.println(toString()+"#startElement("+
208                                "element={"+element+"},"+
209                                "attributes=..."+attributes+
210                                ")");
211         }
212
213         for(int i = 0; i < fLocationPaths.length; i++) {
214             // push context
215
int startStep = fCurrentStep[i];
216             fStepIndexes[i].push(startStep);
217
218             // try next xpath, if not matching
219
if ((fMatched[i] & MATCHED_DESCENDANT) == MATCHED || fNoMatchDepth[i] > 0) {
220                 fNoMatchDepth[i]++;
221                 continue;
222             }
223             if((fMatched[i] & MATCHED_DESCENDANT) == MATCHED_DESCENDANT) {
224                 fMatched[i] = MATCHED_DESCENDANT_PREVIOUS;
225             }
226
227             if (DEBUG_STACK) {
228                 System.out.println(toString()+": "+fStepIndexes[i]);
229             }
230
231             // consume self::node() steps
232
XPath.Step[] steps = fLocationPaths[i].steps;
233             while (fCurrentStep[i] < steps.length &&
234                     steps[fCurrentStep[i]].axis.type == XPath.Axis.SELF) {
235                 if (DEBUG_MATCH) {
236                     XPath.Step step = steps[fCurrentStep[i]];
237                     System.out.println(toString()+" [SELF] MATCHED!");
238                 }
239                 fCurrentStep[i]++;
240             }
241             if (fCurrentStep[i] == steps.length) {
242                 if (DEBUG_MATCH) {
243                     System.out.println(toString()+" XPath MATCHED!");
244                 }
245                 fMatched[i] = MATCHED;
246                 continue;
247             }
248
249             // now if the current step is a descendant step, we let the next
250
// step do its thing; if it fails, we reset ourselves
251
// to look at this step for next time we're called.
252
// so first consume all descendants:
253
int descendantStep = fCurrentStep[i];
254             while(fCurrentStep[i] < steps.length && steps[fCurrentStep[i]].axis.type == XPath.Axis.DESCENDANT) {
255                 if (DEBUG_MATCH) {
256                     XPath.Step step = steps[fCurrentStep[i]];
257                     System.out.println(toString()+" [DESCENDANT] MATCHED!");
258                 }
259                 fCurrentStep[i]++;
260             }
261             boolean sawDescendant = fCurrentStep[i] > descendantStep;
262             if (fCurrentStep[i] == steps.length) {
263                 if (DEBUG_MATCH) {
264                     System.out.println(toString()+" XPath DIDN'T MATCH!");
265                 }
266                 fNoMatchDepth[i]++;
267                 if (DEBUG_MATCH) {
268                     System.out.println(toString()+" [CHILD] after NO MATCH");
269                 }
270                 continue;
271             }
272
273             // match child::... step, if haven't consumed any self::node()
274
if ((fCurrentStep[i] == startStep || fCurrentStep[i] > descendantStep) &&
275                 steps[fCurrentStep[i]].axis.type == XPath.Axis.CHILD) {
276                 XPath.Step step = steps[fCurrentStep[i]];
277                 XPath.NodeTest nodeTest = step.nodeTest;
278                 if (DEBUG_MATCH) {
279                     System.out.println(toString()+" [CHILD] before");
280                 }
281                 if (nodeTest.type == XPath.NodeTest.QNAME) {
282                     if (!nodeTest.name.equals(element)) {
283                         if(fCurrentStep[i] > descendantStep) {
284                             fCurrentStep[i] = descendantStep;
285                             continue;
286                         }
287                         fNoMatchDepth[i]++;
288                         if (DEBUG_MATCH) {
289                             System.out.println(toString()+" [CHILD] after NO MATCH");
290                         }
291                         continue;
292                     }
293                 }
294                 fCurrentStep[i]++;
295                 if (DEBUG_MATCH) {
296                     System.out.println(toString()+" [CHILD] after MATCHED!");
297                 }
298             }
299             if (fCurrentStep[i] == steps.length) {
300                 if(sawDescendant) {
301                     fCurrentStep[i] = descendantStep;
302                     fMatched[i] = MATCHED_DESCENDANT;
303                 } else {
304                     fMatched[i] = MATCHED;
305                 }
306                 continue;
307             }
308
309             // match attribute::... step
310
if (fCurrentStep[i] < steps.length &&
311                 steps[fCurrentStep[i]].axis.type == XPath.Axis.ATTRIBUTE) {
312                 if (DEBUG_MATCH) {
313                     System.out.println(toString()+" [ATTRIBUTE] before");
314                 }
315                 int attrCount = attributes.getLength();
316                 if (attrCount > 0) {
317                     XPath.NodeTest nodeTest = steps[fCurrentStep[i]].nodeTest;
318
319                     for (int aIndex = 0; aIndex < attrCount; aIndex++) {
320                         attributes.getName(aIndex, fQName);
321                         if (nodeTest.type != XPath.NodeTest.QNAME ||
322                             nodeTest.name.equals(fQName)) {
323                             fCurrentStep[i]++;
324                             if (fCurrentStep[i] == steps.length) {
325                                 fMatched[i] = MATCHED_ATTRIBUTE;
326                                 int j=0;
327                                 for(; j<i && ((fMatched[j] & MATCHED) != MATCHED); j++);
328                                 if(j==i) {
329                                     AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations(aIndex).getItem(Constants.ATTRIBUTE_PSVI);
330                                     fMatchedString = attrPSVI.getActualNormalizedValue();
331                                     matched(fMatchedString, attrPSVI.getActualNormalizedValueType(), attrPSVI.getItemValueTypes(), false);
332                                 }
333                             }
334                             break;
335                         }
336                     }
337                 }
338                 if ((fMatched[i] & MATCHED) != MATCHED) {
339                     if(fCurrentStep[i] > descendantStep) {
340                         fCurrentStep[i] = descendantStep;
341                         continue;
342                     }
343                     fNoMatchDepth[i]++;
344                     if (DEBUG_MATCH) {
345                         System.out.println(toString()+" [ATTRIBUTE] after");
346                     }
347                     continue;
348                 }
349                 if (DEBUG_MATCH) {
350                     System.out.println(toString()+" [ATTRIBUTE] after MATCHED!");
351                 }
352             }
353         }
354
355     }
356     // startElement(QName,XMLAttrList,int)
357

358     /**
359        * @param element
360        * name of the element.
361        * @param type
362        * content type of this element. IOW, the XML schema type
363        * of the <tt>value</tt>. Note that this may not be the type declared
364        * in the element declaration, but it is "the actual type". For example,
365        * if the XML is &lt;foo xsi:type="xs:string">aaa&lt;/foo>, this
366        * parameter will be "xs:string".
367        * @param nillable - nillable
368        * true if the element declaration is nillable.
369        * @param value - actual value
370        * the typed value of the content of this element.
371        */

372     public void endElement(QName element, XSTypeDefinition type, boolean nillable, Object JavaDoc value, short valueType, ShortList itemValueType) {
373         if (DEBUG_METHODS2) {
374             System.out.println(toString()+"#endElement("+
375                                "element={"+element+"},"+
376                                ")");
377         }
378         for(int i = 0; i<fLocationPaths.length; i++) {
379             // go back a step
380
fCurrentStep[i] = fStepIndexes[i].pop();
381
382             // don't do anything, if not matching
383
if (fNoMatchDepth[i] > 0) {
384                 fNoMatchDepth[i]--;
385             }
386
387             // signal match, if appropriate
388
else {
389                 int j=0;
390                 for(; j<i && ((fMatched[j] & MATCHED) != MATCHED); j++);
391                 if ((j<i) || (fMatched[j] == 0) ||
392                         ((fMatched[j] & MATCHED_ATTRIBUTE) == MATCHED_ATTRIBUTE)) {
393                     continue;
394                 }
395                 // only certain kinds of matchers actually
396
// match element content. This permits
397
// them a way to override this to do nothing
398
// and hopefully save a few operations.
399
handleContent(type, nillable, value, valueType, itemValueType);
400                 fMatched[i] = 0;
401             }
402
403             if (DEBUG_STACK) {
404                 System.out.println(toString()+": "+fStepIndexes[i]);
405             }
406         }
407
408     } // endElement(QName)
409

410     //
411
// Object methods
412
//
413

414     /** Returns a string representation of this object. */
415     public String JavaDoc toString() {
416         /***
417         return fLocationPath.toString();
418         /***/

419         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
420         String JavaDoc s = super.toString();
421         int index2 = s.lastIndexOf('.');
422         if (index2 != -1) {
423             s = s.substring(index2 + 1);
424         }
425         str.append(s);
426         for(int i =0;i<fLocationPaths.length; i++) {
427             str.append('[');
428             XPath.Step[] steps = fLocationPaths[i].steps;
429             for (int j = 0; j < steps.length; j++) {
430                 if (j == fCurrentStep[i]) {
431                     str.append('^');
432                 }
433                 str.append(steps[j].toString());
434                 if (j < steps.length - 1) {
435                     str.append('/');
436                 }
437             }
438             if (fCurrentStep[i] == steps.length) {
439                 str.append('^');
440             }
441             str.append(']');
442             str.append(',');
443         }
444         return str.toString();
445     } // toString():String
446

447     //
448
// Private methods
449
//
450

451     /** Normalizes text. */
452     private String JavaDoc normalize(String JavaDoc s) {
453         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
454         int length = s.length();
455         for (int i = 0; i < length; i++) {
456             char c = s.charAt(i);
457             switch (c) {
458                 case '\n': {
459                     str.append("\\n");
460                     break;
461                 }
462                 default: {
463                     str.append(c);
464                 }
465             }
466         }
467         return str.toString();
468     } // normalize(String):String
469

470     //
471
// MAIN
472
//
473

474     // NOTE: The main of this class is here for debugging purposes.
475
// However, javac (JDK 1.1.8) has an internal compiler
476
// error when compiling. Jikes has no problem, though.
477
//
478
// If you want to use this main, use Jikes to compile but
479
// *never* check in this code to CVS without commenting it
480
// out. -Ac
481

482     /** Main program. */
483     /***
484     public static void main(String[] argv) throws XNIException {
485
486         if (DEBUG_ANY) {
487             for (int i = 0; i < argv.length; i++) {
488                 final String expr = argv[i];
489                 final XPath xpath = new XPath(expr, symbols, null);
490                 final XPathMatcher matcher = new XPathMatcher(xpath, true);
491                 org.apache.xerces.parsers.SAXParser parser =
492                     new org.apache.xerces.parsers.SAXParser(symbols) {
493                     public void startDocument() throws XNIException {
494                         matcher.startDocumentFragment(symbols, null);
495                     }
496                     public void startElement(QName element, XMLAttrList attributes, int handle) throws XNIException {
497                         matcher.startElement(element, attributes, handle);
498                     }
499                     public void characters(char[] ch, int offset, int length) throws XNIException {
500                         matcher.characters(ch, offset, length);
501                     }
502                     public void endElement(QName element) throws XNIException {
503                         matcher.endElement(element);
504                     }
505                     public void endDocument() throws XNIException {
506                         matcher.endDocumentFragment();
507                     }
508                 };
509                 System.out.println("#### argv["+i+"]: \""+expr+"\" -> \""+xpath.toString()+'"');
510                 final String uri = argv[++i];
511                 System.out.println("#### argv["+i+"]: "+uri);
512                 parser.parse(uri);
513             }
514         }
515
516     } // main(String[])
517     /***/

518
519 } // class XPathMatcher
520
Popular Tags