KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001, 2002 The Apache Software Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Xerces" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 1999, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package com.sun.org.apache.xerces.internal.impl.xs.identity;
59
60 import com.sun.org.apache.xerces.internal.impl.Constants;
61 import com.sun.org.apache.xerces.internal.impl.xpath.XPath;
62 import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
63 import com.sun.org.apache.xerces.internal.util.IntStack;
64 import com.sun.org.apache.xerces.internal.xni.QName;
65 import com.sun.org.apache.xerces.internal.xni.XMLAttributes;
66 import com.sun.org.apache.xerces.internal.xs.AttributePSVI;
67
68
69 /**
70  * XPath matcher.
71  *
72  * @author Andy Clark, IBM
73  *
74  * @version $Id: XPathMatcher.java,v 1.22 2004/02/10 21:26:03 kohsuke Exp $
75  */

76 public class XPathMatcher {
77
78     //
79
// Constants
80
//
81

82     // debugging
83

84     /** Compile to true to debug everything. */
85     protected static final boolean DEBUG_ALL = false;
86
87     /** Compile to true to debug method callbacks. */
88     protected static final boolean DEBUG_METHODS = false || DEBUG_ALL;
89
90     /** Compile to true to debug important method callbacks. */
91     protected static final boolean DEBUG_METHODS2 = false || DEBUG_METHODS || DEBUG_ALL;
92
93     /** Compile to true to debug the <em>really</em> important methods. */
94     protected static final boolean DEBUG_METHODS3 = false || DEBUG_METHODS || DEBUG_ALL;
95
96     /** Compile to true to debug match. */
97     protected static final boolean DEBUG_MATCH = false || DEBUG_ALL;
98
99     /** Compile to true to debug step index stack. */
100     protected static final boolean DEBUG_STACK = false || DEBUG_ALL;
101
102     /** Don't touch this value unless you add more debug constants. */
103     protected static final boolean DEBUG_ANY = DEBUG_METHODS ||
104                                                DEBUG_METHODS2 ||
105                                                DEBUG_METHODS3 ||
106                                                DEBUG_MATCH ||
107                                                DEBUG_STACK;
108
109     // constants describing whether a match was made,
110
// and if so how.
111
// matched any way
112
protected static final int MATCHED = 1;
113     // matched on the attribute axis
114
protected static final int MATCHED_ATTRIBUTE = 3;
115     // matched on the descendant-or-self axixs
116
protected static final int MATCHED_DESCENDANT = 5;
117     // matched some previous (ancestor) node on the descendant-or-self-axis, but not this node
118
protected static final int MATCHED_DESCENDANT_PREVIOUS = 13;
119
120     //
121
// Data
122
//
123

124     /** XPath location path. */
125     private XPath.LocationPath[] fLocationPaths;
126
127     /** True if XPath has been matched. */
128     private int[] fMatched;
129
130     /** The matching string. */
131     protected Object JavaDoc fMatchedString;
132
133     /** Integer stack of step indexes. */
134     private IntStack[] fStepIndexes;
135
136     /** Current step. */
137     private int[] fCurrentStep;
138
139     /**
140      * No match depth. The value of this field will be zero while
141      * matching is successful for the given xpath expression.
142      */

143     private int [] fNoMatchDepth;
144     
145     final QName fQName = new QName();
146
147     XSTypeDefinition fCurrMatchedType = null;
148     //
149
// Constructors
150
//
151

152     /**
153      * Constructs an XPath matcher that implements a document fragment
154      * handler.
155      *
156      * @param xpath The xpath.
157      */

158     public XPathMatcher(XPath xpath) {
159         fLocationPaths = xpath.getLocationPaths();
160         fStepIndexes = new IntStack[fLocationPaths.length];
161         for(int i=0; i<fStepIndexes.length; i++) fStepIndexes[i] = new IntStack();
162         fCurrentStep = new int[fLocationPaths.length];
163         fNoMatchDepth = new int[fLocationPaths.length];
164         fMatched = new int[fLocationPaths.length];
165     } // <init>(XPath)
166

167     //
168
// Public methods
169
//
170

171     /**
172      * Returns value of first member of fMatched that
173      * is nonzero.
174      */

175     public boolean isMatched() {
176         // xpath has been matched if any one of the members of the union have matched.
177
for (int i=0; i < fLocationPaths.length; i++)
178             if (((fMatched[i] & MATCHED) == MATCHED)
179                     && ((fMatched[i] & MATCHED_DESCENDANT_PREVIOUS) != MATCHED_DESCENDANT_PREVIOUS)
180                     && ((fNoMatchDepth[i] == 0)
181                     || ((fMatched[i] & MATCHED_DESCENDANT) == MATCHED_DESCENDANT)))
182                 return true;
183
184         return false;
185     } // isMatched():int
186

187     //
188
// Protected methods
189
//
190

191     // a place-holder method; to be overridden by subclasses
192
// that care about matching element content.
193
protected void handleContent(XSTypeDefinition type, boolean nillable, Object JavaDoc value) {
194     }
195
196     /**
197      * This method is called when the XPath handler matches the
198      * XPath expression. Subclasses can override this method to
199      * provide default handling upon a match.
200      */

201     protected void matched(Object JavaDoc actualValue, boolean isNil) {
202         if (DEBUG_METHODS3) {
203             System.out.println(toString()+"#matched(\""+actualValue+"\")");
204         }
205     } // matched(String content, XSSimpleType val)
206

207     //
208
// ~XMLDocumentFragmentHandler methods
209
//
210

211     /**
212      * The start of the document fragment.
213      *
214      * @param context The namespace scope in effect at the
215      * start of this document fragment.
216      */

217     public void startDocumentFragment(){
218         if (DEBUG_METHODS) {
219             System.out.println(toString()+"#startDocumentFragment("+
220                                ")");
221         }
222
223         // reset state
224
fMatchedString = null;
225         for(int i = 0; i < fLocationPaths.length; i++) {
226             fStepIndexes[i].clear();
227             fCurrentStep[i] = 0;
228             fNoMatchDepth[i] = 0;
229             fMatched[i] = 0;
230         }
231
232
233     } // startDocumentFragment(SymbolTable)
234

235     /**
236      * The start of an element. If the document specifies the start element
237      * by using an empty tag, then the startElement method will immediately
238      * be followed by the endElement method, with no intervening methods.
239      *
240      * @param element The name of the element.
241      * @param attributes The element attributes.
242      * @param type: The element's type
243      *
244      * @throws SAXException Thrown by handler to signal an error.
245      */

246     public void startElement(QName element, XMLAttributes attributes){
247         if (DEBUG_METHODS2) {
248             System.out.println(toString()+"#startElement("+
249                                "element={"+element+"},"+
250                                "attributes=..."+attributes+
251                                ")");
252         }
253
254         for(int i = 0; i < fLocationPaths.length; i++) {
255             // push context
256
int startStep = fCurrentStep[i];
257             fStepIndexes[i].push(startStep);
258
259             // try next xpath, if not matching
260
if ((fMatched[i] & MATCHED_DESCENDANT) == MATCHED || fNoMatchDepth[i] > 0) {
261                 fNoMatchDepth[i]++;
262                 continue;
263             }
264             if((fMatched[i] & MATCHED_DESCENDANT) == MATCHED_DESCENDANT) {
265                 fMatched[i] = MATCHED_DESCENDANT_PREVIOUS;
266             }
267
268             if (DEBUG_STACK) {
269                 System.out.println(toString()+": "+fStepIndexes[i]);
270             }
271
272             // consume self::node() steps
273
XPath.Step[] steps = fLocationPaths[i].steps;
274             while (fCurrentStep[i] < steps.length &&
275                     steps[fCurrentStep[i]].axis.type == XPath.Axis.SELF) {
276                 if (DEBUG_MATCH) {
277                     XPath.Step step = steps[fCurrentStep[i]];
278                     System.out.println(toString()+" [SELF] MATCHED!");
279                 }
280                 fCurrentStep[i]++;
281             }
282             if (fCurrentStep[i] == steps.length) {
283                 if (DEBUG_MATCH) {
284                     System.out.println(toString()+" XPath MATCHED!");
285                 }
286                 fMatched[i] = MATCHED;
287                 continue;
288             }
289
290             // now if the current step is a descendant step, we let the next
291
// step do its thing; if it fails, we reset ourselves
292
// to look at this step for next time we're called.
293
// so first consume all descendants:
294
int descendantStep = fCurrentStep[i];
295             while(fCurrentStep[i] < steps.length && steps[fCurrentStep[i]].axis.type == XPath.Axis.DESCENDANT) {
296                 if (DEBUG_MATCH) {
297                     XPath.Step step = steps[fCurrentStep[i]];
298                     System.out.println(toString()+" [DESCENDANT] MATCHED!");
299                 }
300                 fCurrentStep[i]++;
301             }
302             boolean sawDescendant = fCurrentStep[i] > descendantStep;
303             if (fCurrentStep[i] == steps.length) {
304                 if (DEBUG_MATCH) {
305                     System.out.println(toString()+" XPath DIDN'T MATCH!");
306                 }
307                 fNoMatchDepth[i]++;
308                 if (DEBUG_MATCH) {
309                     System.out.println(toString()+" [CHILD] after NO MATCH");
310                 }
311                 continue;
312             }
313
314             // match child::... step, if haven't consumed any self::node()
315
if ((fCurrentStep[i] == startStep || fCurrentStep[i] > descendantStep) &&
316                 steps[fCurrentStep[i]].axis.type == XPath.Axis.CHILD) {
317                 XPath.Step step = steps[fCurrentStep[i]];
318                 XPath.NodeTest nodeTest = step.nodeTest;
319                 if (DEBUG_MATCH) {
320                     System.out.println(toString()+" [CHILD] before");
321                 }
322                 if (nodeTest.type == XPath.NodeTest.QNAME) {
323                     if (!nodeTest.name.equals(element)) {
324                         if(fCurrentStep[i] > descendantStep) {
325                             fCurrentStep[i] = descendantStep;
326                             continue;
327                         }
328                         fNoMatchDepth[i]++;
329                         if (DEBUG_MATCH) {
330                             System.out.println(toString()+" [CHILD] after NO MATCH");
331                         }
332                         continue;
333                     }
334                 }
335                 fCurrentStep[i]++;
336                 if (DEBUG_MATCH) {
337                     System.out.println(toString()+" [CHILD] after MATCHED!");
338                 }
339             }
340             if (fCurrentStep[i] == steps.length) {
341                 if(sawDescendant) {
342                     fCurrentStep[i] = descendantStep;
343                     fMatched[i] = MATCHED_DESCENDANT;
344                 } else {
345                     fMatched[i] = MATCHED;
346                 }
347                 continue;
348             }
349
350             // match attribute::... step
351
if (fCurrentStep[i] < steps.length &&
352                 steps[fCurrentStep[i]].axis.type == XPath.Axis.ATTRIBUTE) {
353                 if (DEBUG_MATCH) {
354                     System.out.println(toString()+" [ATTRIBUTE] before");
355                 }
356                 int attrCount = attributes.getLength();
357                 if (attrCount > 0) {
358                     XPath.NodeTest nodeTest = steps[fCurrentStep[i]].nodeTest;
359
360                     for (int aIndex = 0; aIndex < attrCount; aIndex++) {
361                         attributes.getName(aIndex, fQName);
362                         if (nodeTest.type != XPath.NodeTest.QNAME ||
363                             nodeTest.name.equals(fQName)) {
364                             fCurrentStep[i]++;
365                             if (fCurrentStep[i] == steps.length) {
366                                 fMatched[i] = MATCHED_ATTRIBUTE;
367                                 int j=0;
368                                 for(; j<i && ((fMatched[j] & MATCHED) != MATCHED); j++);
369                                 if(j==i) {
370                                     AttributePSVI attrPSVI = (AttributePSVI)attributes.getAugmentations(aIndex).getItem(Constants.ATTRIBUTE_PSVI);
371                                     fMatchedString = attrPSVI.getActualNormalizedValue();
372                                     fCurrMatchedType = attrPSVI.getTypeDefinition();
373                                     matched(fMatchedString, false);
374                                 }
375                             }
376                             break;
377                         }
378                     }
379                 }
380                 if ((fMatched[i] & MATCHED) != MATCHED) {
381                     if(fCurrentStep[i] > descendantStep) {
382                         fCurrentStep[i] = descendantStep;
383                         continue;
384                     }
385                     fNoMatchDepth[i]++;
386                     if (DEBUG_MATCH) {
387                         System.out.println(toString()+" [ATTRIBUTE] after");
388                     }
389                     continue;
390                 }
391                 if (DEBUG_MATCH) {
392                     System.out.println(toString()+" [ATTRIBUTE] after MATCHED!");
393                 }
394             }
395         }
396
397     }
398     // startElement(QName,XMLAttrList,int)
399

400     /**
401        * @param element
402        * name of the element.
403        * @param type
404        * content type of this element. IOW, the XML schema type
405        * of the <tt>value</tt>. Note that this may not be the type declared
406        * in the element declaration, but it is "the actual type". For example,
407        * if the XML is &lt;foo xsi:type="xs:string">aaa&lt;/foo>, this
408        * parameter will be "xs:string".
409        * @param nillable - nillable
410        * true if the element declaration is nillable.
411        * @param value - actual value
412        * the typed value of the content of this element.
413        */

414     public void endElement(QName element, XSTypeDefinition type, boolean nillable, Object JavaDoc value ) {
415         if (DEBUG_METHODS2) {
416             System.out.println(toString()+"#endElement("+
417                                "element={"+element+"},"+
418                                ")");
419         }
420         for(int i = 0; i<fLocationPaths.length; i++) {
421             // go back a step
422
fCurrentStep[i] = fStepIndexes[i].pop();
423
424             // don't do anything, if not matching
425
if (fNoMatchDepth[i] > 0) {
426                 fNoMatchDepth[i]--;
427             }
428
429             // signal match, if appropriate
430
else {
431                 int j=0;
432                 for(; j<i && ((fMatched[j] & MATCHED) != MATCHED); j++);
433                 if ((j<i) || (fMatched[j] == 0) ||
434                         ((fMatched[j] & MATCHED_ATTRIBUTE) == MATCHED_ATTRIBUTE)) {
435                     continue;
436                 }
437                 // only certain kinds of matchers actually
438
// match element content. This permits
439
// them a way to override this to do nothing
440
// and hopefully save a few operations.
441
handleContent(type, nillable, value);
442                 fMatched[i] = 0;
443             }
444
445             if (DEBUG_STACK) {
446                 System.out.println(toString()+": "+fStepIndexes[i]);
447             }
448         }
449
450     } // endElement(QName)
451

452     //
453
// Object methods
454
//
455

456     /** Returns a string representation of this object. */
457     public String JavaDoc toString() {
458         /***
459         return fLocationPath.toString();
460         /***/

461         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
462         String JavaDoc s = super.toString();
463         int index2 = s.lastIndexOf('.');
464         if (index2 != -1) {
465             s = s.substring(index2 + 1);
466         }
467         str.append(s);
468         for(int i =0;i<fLocationPaths.length; i++) {
469             str.append('[');
470             XPath.Step[] steps = fLocationPaths[i].steps;
471             for (int j = 0; j < steps.length; j++) {
472                 if (j == fCurrentStep[i]) {
473                     str.append('^');
474                 }
475                 str.append(steps[j].toString());
476                 if (j < steps.length - 1) {
477                     str.append('/');
478                 }
479             }
480             if (fCurrentStep[i] == steps.length) {
481                 str.append('^');
482             }
483             str.append(']');
484             str.append(',');
485         }
486         return str.toString();
487     } // toString():String
488

489     //
490
// Private methods
491
//
492

493     /** Normalizes text. */
494     private String JavaDoc normalize(String JavaDoc s) {
495         StringBuffer JavaDoc str = new StringBuffer JavaDoc();
496         int length = s.length();
497         for (int i = 0; i < length; i++) {
498             char c = s.charAt(i);
499             switch (c) {
500                 case '\n': {
501                     str.append("\\n");
502                     break;
503                 }
504                 default: {
505                     str.append(c);
506                 }
507             }
508         }
509         return str.toString();
510     } // normalize(String):String
511

512     public XSTypeDefinition getCurrentMatchedType(){
513         return fCurrMatchedType;
514     }
515
516     //
517
// MAIN
518
//
519

520     // NOTE: The main of this class is here for debugging purposes.
521
// However, javac (JDK 1.1.8) has an internal compiler
522
// error when compiling. Jikes has no problem, though.
523
//
524
// If you want to use this main, use Jikes to compile but
525
// *never* check in this code to CVS without commenting it
526
// out. -Ac
527

528     /** Main program. */
529     /***
530     public static void main(String[] argv) throws XNIException {
531
532         if (DEBUG_ANY) {
533             for (int i = 0; i < argv.length; i++) {
534                 final String expr = argv[i];
535                 final XPath xpath = new XPath(expr, symbols, null);
536                 final XPathMatcher matcher = new XPathMatcher(xpath, true);
537                 com.sun.org.apache.xerces.internal.parsers.SAXParser parser =
538                     new com.sun.org.apache.xerces.internal.parsers.SAXParser(symbols) {
539                     public void startDocument() throws XNIException {
540                         matcher.startDocumentFragment(symbols, null);
541                     }
542                     public void startElement(QName element, XMLAttrList attributes, int handle) throws XNIException {
543                         matcher.startElement(element, attributes, handle);
544                     }
545                     public void characters(char[] ch, int offset, int length) throws XNIException {
546                         matcher.characters(ch, offset, length);
547                     }
548                     public void endElement(QName element) throws XNIException {
549                         matcher.endElement(element);
550                     }
551                     public void endDocument() throws XNIException {
552                         matcher.endDocumentFragment();
553                     }
554                 };
555                 System.out.println("#### argv["+i+"]: \""+expr+"\" -> \""+xpath.toString()+'"');
556                 final String uri = argv[++i];
557                 System.out.println("#### argv["+i+"]: "+uri);
558                 parser.parse(uri);
559             }
560         }
561
562     } // main(String[])
563     /***/

564
565 } // class XPathMatcher
566
Popular Tags