KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xalan > internal > xsltc > runtime > BasisLibrary


1 /*
2  * Copyright 2001-2004 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  * $Id: BasisLibrary.java,v 1.1.2.1 2006/09/19 01:07:26 jeffsuttor Exp $
18  */

19
20 package com.sun.org.apache.xalan.internal.xsltc.runtime;
21
22 import java.text.DecimalFormat JavaDoc;
23 import java.text.FieldPosition JavaDoc;
24 import java.text.MessageFormat JavaDoc;
25 import java.text.NumberFormat JavaDoc;
26 import java.util.Locale JavaDoc;
27 import java.util.ResourceBundle JavaDoc;
28
29 import javax.xml.transform.dom.DOMSource JavaDoc;
30
31 import com.sun.org.apache.xalan.internal.xsltc.DOM;
32 import com.sun.org.apache.xalan.internal.xsltc.Translet;
33 import com.sun.org.apache.xalan.internal.xsltc.dom.AbsoluteIterator;
34 import com.sun.org.apache.xalan.internal.xsltc.dom.Axis;
35 import com.sun.org.apache.xalan.internal.xsltc.dom.DOMAdapter;
36 import com.sun.org.apache.xalan.internal.xsltc.dom.MultiDOM;
37 import com.sun.org.apache.xalan.internal.xsltc.dom.SingletonIterator;
38 import com.sun.org.apache.xalan.internal.xsltc.dom.StepIterator;
39 import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
40 import com.sun.org.apache.xml.internal.dtm.DTMManager;
41 import com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBase;
42
43 import org.w3c.dom.DOMException JavaDoc;
44 import org.w3c.dom.Document JavaDoc;
45 import org.w3c.dom.NodeList JavaDoc;
46 import org.xml.sax.SAXException JavaDoc;
47 import com.sun.org.apache.xml.internal.serializer.NamespaceMappings;
48 import com.sun.org.apache.xml.internal.serializer.SerializationHandler;
49 import com.sun.org.apache.xml.internal.utils.XMLChar;
50
51 /**
52  * Standard XSLT functions. All standard functions expect the current node
53  * and the DOM as their last two arguments.
54  */

55 public final class BasisLibrary implements Operators {
56
57     private final static String JavaDoc EMPTYSTRING = "";
58
59     /**
60      * Standard function count(node-set)
61      */

62     public static int countF(DTMAxisIterator iterator) {
63     return(iterator.getLast());
64     }
65
66     /**
67      * Standard function position()
68      * @deprecated This method exists only for backwards compatibility with old
69      * translets. New code should not reference it.
70      */

71     public static int positionF(DTMAxisIterator iterator) {
72         return iterator.isReverse()
73                      ? iterator.getLast() - iterator.getPosition() + 1
74                      : iterator.getPosition();
75     }
76
77     /**
78      * XSLT Standard function sum(node-set).
79      * stringToDouble is inlined
80      */

81     public static double sumF(DTMAxisIterator iterator, DOM dom) {
82     try {
83         double result = 0.0;
84         int node;
85         while ((node = iterator.next()) != DTMAxisIterator.END) {
86         result += Double.parseDouble(dom.getStringValueX(node));
87         }
88         return result;
89     }
90     catch (NumberFormatException JavaDoc e) {
91         return Double.NaN;
92     }
93     }
94
95     /**
96      * XSLT Standard function string()
97      */

98     public static String JavaDoc stringF(int node, DOM dom) {
99     return dom.getStringValueX(node);
100     }
101
102     /**
103      * XSLT Standard function string(value)
104      */

105     public static String JavaDoc stringF(Object JavaDoc obj, DOM dom) {
106     if (obj instanceof DTMAxisIterator) {
107         return dom.getStringValueX(((DTMAxisIterator)obj).reset().next());
108     }
109     else if (obj instanceof Node) {
110         return dom.getStringValueX(((Node)obj).node);
111     }
112     else if (obj instanceof DOM) {
113         return ((DOM)obj).getStringValue();
114     }
115     else {
116         return obj.toString();
117     }
118     }
119
120     /**
121      * XSLT Standard function string(value)
122      */

123     public static String JavaDoc stringF(Object JavaDoc obj, int node, DOM dom) {
124     if (obj instanceof DTMAxisIterator) {
125         return dom.getStringValueX(((DTMAxisIterator)obj).reset().next());
126     }
127     else if (obj instanceof Node) {
128         return dom.getStringValueX(((Node)obj).node);
129     }
130     else if (obj instanceof DOM) {
131         // When the first argument is a DOM we want the whole fecking
132
// DOM and not just a single node - that would not make sense.
133
//return ((DOM)obj).getStringValueX(node);
134
return ((DOM)obj).getStringValue();
135     }
136     else if (obj instanceof Double JavaDoc) {
137         Double JavaDoc d = (Double JavaDoc)obj;
138         final String JavaDoc result = d.toString();
139         final int length = result.length();
140         if ((result.charAt(length-2)=='.') &&
141         (result.charAt(length-1) == '0'))
142         return result.substring(0, length-2);
143         else
144         return result;
145     }
146     else {
147         if (obj != null)
148         return obj.toString();
149         else
150         return stringF(node, dom);
151     }
152     }
153
154     /**
155      * XSLT Standard function number()
156      */

157     public static double numberF(int node, DOM dom) {
158     return stringToReal(dom.getStringValueX(node));
159     }
160
161     /**
162      * XSLT Standard function number(value)
163      */

164     public static double numberF(Object JavaDoc obj, DOM dom) {
165     if (obj instanceof Double JavaDoc) {
166         return ((Double JavaDoc) obj).doubleValue();
167     }
168     else if (obj instanceof Integer JavaDoc) {
169         return ((Integer JavaDoc) obj).doubleValue();
170     }
171     else if (obj instanceof Boolean JavaDoc) {
172         return ((Boolean JavaDoc) obj).booleanValue() ? 1.0 : 0.0;
173     }
174     else if (obj instanceof String JavaDoc) {
175         return stringToReal((String JavaDoc) obj);
176     }
177     else if (obj instanceof DTMAxisIterator) {
178         DTMAxisIterator iter = (DTMAxisIterator) obj;
179         return stringToReal(dom.getStringValueX(iter.reset().next()));
180     }
181     else if (obj instanceof Node) {
182         return stringToReal(dom.getStringValueX(((Node) obj).node));
183     }
184     else if (obj instanceof DOM) {
185         return stringToReal(((DOM) obj).getStringValue());
186     }
187     else {
188         final String JavaDoc className = obj.getClass().getName();
189         runTimeError(INVALID_ARGUMENT_ERR, className, "number()");
190         return 0.0;
191     }
192     }
193
194     /**
195      * XSLT Standard function round()
196      */

197     public static double roundF(double d) {
198             return (d<-0.5 || d>0.0)?Math.floor(d+0.5):((d==0.0)?
199                         d:(Double.isNaN(d)?Double.NaN:-0.0));
200     }
201
202     /**
203      * XSLT Standard function boolean()
204      */

205     public static boolean booleanF(Object JavaDoc obj) {
206     if (obj instanceof Double JavaDoc) {
207         final double temp = ((Double JavaDoc) obj).doubleValue();
208         return temp != 0.0 && !Double.isNaN(temp);
209     }
210     else if (obj instanceof Integer JavaDoc) {
211         return ((Integer JavaDoc) obj).doubleValue() != 0;
212     }
213     else if (obj instanceof Boolean JavaDoc) {
214         return ((Boolean JavaDoc) obj).booleanValue();
215     }
216     else if (obj instanceof String JavaDoc) {
217         return !((String JavaDoc) obj).equals(EMPTYSTRING);
218     }
219     else if (obj instanceof DTMAxisIterator) {
220         DTMAxisIterator iter = (DTMAxisIterator) obj;
221         return iter.reset().next() != DTMAxisIterator.END;
222     }
223     else if (obj instanceof Node) {
224         return true;
225     }
226     else if (obj instanceof DOM) {
227         String JavaDoc temp = ((DOM) obj).getStringValue();
228         return !temp.equals(EMPTYSTRING);
229     }
230     else {
231         final String JavaDoc className = obj.getClass().getName();
232         runTimeError(INVALID_ARGUMENT_ERR, className, "number()");
233     }
234     return false;
235     }
236
237     /**
238      * XSLT Standard function substring(). Must take a double because of
239      * conversions resulting into NaNs and rounding.
240      */

241     public static String JavaDoc substringF(String JavaDoc value, double start) {
242     try {
243         final int strlen = value.length();
244         int istart = (int)Math.round(start) - 1;
245
246         if (Double.isNaN(start)) return(EMPTYSTRING);
247         if (istart > strlen) return(EMPTYSTRING);
248         if (istart < 1) istart = 0;
249
250         return value.substring(istart);
251     }
252     catch (IndexOutOfBoundsException JavaDoc e) {
253         runTimeError(RUN_TIME_INTERNAL_ERR, "substring()");
254         return null;
255     }
256     }
257
258     /**
259      * XSLT Standard function substring(). Must take a double because of
260      * conversions resulting into NaNs and rounding.
261      */

262     public static String JavaDoc substringF(String JavaDoc value, double start, double length) {
263     try {
264         final int strlen = value.length();
265         int istart = (int)Math.round(start) - 1;
266         int isum = istart + (int)Math.round(length);
267
268         if (Double.isInfinite(length)) isum = Integer.MAX_VALUE;
269
270         if (Double.isNaN(start) || Double.isNaN(length))
271         return(EMPTYSTRING);
272         if (Double.isInfinite(start)) return(EMPTYSTRING);
273         if (istart > strlen) return(EMPTYSTRING);
274         if (isum < 0) return(EMPTYSTRING);
275         if (istart < 0) istart = 0;
276
277         if (isum > strlen)
278         return value.substring(istart);
279         else
280         return value.substring(istart, isum);
281     }
282     catch (IndexOutOfBoundsException JavaDoc e) {
283         runTimeError(RUN_TIME_INTERNAL_ERR, "substring()");
284         return null;
285     }
286     }
287
288     /**
289      * XSLT Standard function substring-after().
290      */

291     public static String JavaDoc substring_afterF(String JavaDoc value, String JavaDoc substring) {
292     final int index = value.indexOf(substring);
293     if (index >= 0)
294         return value.substring(index + substring.length());
295     else
296         return EMPTYSTRING;
297     }
298
299     /**
300      * XSLT Standard function substring-before().
301      */

302     public static String JavaDoc substring_beforeF(String JavaDoc value, String JavaDoc substring) {
303     final int index = value.indexOf(substring);
304     if (index >= 0)
305         return value.substring(0, index);
306     else
307         return EMPTYSTRING;
308     }
309
310     /**
311      * XSLT Standard function translate().
312      */

313     public static String JavaDoc translateF(String JavaDoc value, String JavaDoc from, String JavaDoc to) {
314     final int tol = to.length();
315     final int froml = from.length();
316     final int valuel = value.length();
317
318     final StringBuffer JavaDoc result = new StringBuffer JavaDoc();
319     for (int j, i = 0; i < valuel; i++) {
320         final char ch = value.charAt(i);
321         for (j = 0; j < froml; j++) {
322         if (ch == from.charAt(j)) {
323             if (j < tol)
324             result.append(to.charAt(j));
325             break;
326         }
327         }
328         if (j == froml)
329         result.append(ch);
330     }
331     return result.toString();
332     }
333
334     /**
335      * XSLT Standard function normalize-space().
336      */

337     public static String JavaDoc normalize_spaceF(int node, DOM dom) {
338     return normalize_spaceF(dom.getStringValueX(node));
339     }
340
341     /**
342      * XSLT Standard function normalize-space(string).
343      */

344     public static String JavaDoc normalize_spaceF(String JavaDoc value) {
345     int i = 0, n = value.length();
346     StringBuffer JavaDoc result = new StringBuffer JavaDoc();
347
348     while (i < n && isWhiteSpace(value.charAt(i)))
349         i++;
350
351     while (true) {
352         while (i < n && !isWhiteSpace(value.charAt(i))) {
353         result.append(value.charAt(i++));
354         }
355         if (i == n)
356         break;
357         while (i < n && isWhiteSpace(value.charAt(i))) {
358         i++;
359         }
360         if (i < n)
361         result.append(' ');
362     }
363     return result.toString();
364     }
365
366     /**
367      * XSLT Standard function generate-id().
368      */

369     public static String JavaDoc generate_idF(int node) {
370     if (node > 0)
371         // Only generate ID if node exists
372
return "N" + node;
373     else
374         // Otherwise return an empty string
375
return EMPTYSTRING;
376     }
377     
378     /**
379      * utility function for calls to local-name().
380      */

381     public static String JavaDoc getLocalName(String JavaDoc value) {
382     int idx = value.lastIndexOf(':');
383     if (idx >= 0) value = value.substring(idx + 1);
384     idx = value.lastIndexOf('@');
385     if (idx >= 0) value = value.substring(idx + 1);
386     return(value);
387     }
388
389     /**
390      * External functions that cannot be resolved are replaced with a call
391      * to this method. This method will generate a runtime errors. A good
392      * stylesheet checks whether the function exists using conditional
393      * constructs, and never really tries to call it if it doesn't exist.
394      * But simple stylesheets may result in a call to this method.
395      * The compiler should generate a warning if it encounters a call to
396      * an unresolved external function.
397      */

398     public static void unresolved_externalF(String JavaDoc name) {
399     runTimeError(EXTERNAL_FUNC_ERR, name);
400     }
401
402     /**
403      * Utility function to throw a runtime error on the use of an extension
404      * function when the secure processing feature is set to true.
405      */

406     public static void unallowed_extension_functionF(String JavaDoc name) {
407         runTimeError(UNALLOWED_EXTENSION_FUNCTION_ERR, name);
408     }
409
410     /**
411      * Utility function to throw a runtime error on the use of an extension
412      * element when the secure processing feature is set to true.
413      */

414     public static void unallowed_extension_elementF(String JavaDoc name) {
415         runTimeError(UNALLOWED_EXTENSION_ELEMENT_ERR, name);
416     }
417
418     /**
419      * Utility function to throw a runtime error for an unsupported element.
420      *
421      * This is only used in forward-compatibility mode, when the control flow
422      * cannot be determined. In 1.0 mode, the error message is emitted at
423      * compile time.
424      */

425     public static void unsupported_ElementF(String JavaDoc qname, boolean isExtension) {
426     if (isExtension)
427         runTimeError(UNSUPPORTED_EXT_ERR, qname);
428     else
429         runTimeError(UNSUPPORTED_XSL_ERR, qname);
430     }
431
432     /**
433      * XSLT Standard function namespace-uri(node-set).
434      */

435     public static String JavaDoc namespace_uriF(DTMAxisIterator iter, DOM dom) {
436     return namespace_uriF(iter.next(), dom);
437     }
438
439     /**
440      * XSLT Standard function system-property(name)
441      */

442     public static String JavaDoc system_propertyF(String JavaDoc name) {
443     if (name.equals("xsl:version"))
444         return("1.0");
445     if (name.equals("xsl:vendor"))
446         return("Apache Software Foundation (Xalan XSLTC)");
447     if (name.equals("xsl:vendor-url"))
448         return("http://xml.apache.org/xalan-j");
449     
450     runTimeError(INVALID_ARGUMENT_ERR, name, "system-property()");
451     return(EMPTYSTRING);
452     }
453
454     /**
455      * XSLT Standard function namespace-uri().
456      */

457     public static String JavaDoc namespace_uriF(int node, DOM dom) {
458     final String JavaDoc value = dom.getNodeName(node);
459     final int colon = value.lastIndexOf(':');
460     if (colon >= 0)
461         return value.substring(0, colon);
462     else
463         return EMPTYSTRING;
464     }
465
466     /**
467      * Implements the object-type() extension function.
468      *
469      * @see <a HREF="http://www.exslt.org/">EXSLT</a>
470      */

471     public static String JavaDoc objectTypeF(Object JavaDoc obj)
472     {
473       if (obj instanceof String JavaDoc)
474         return "string";
475       else if (obj instanceof Boolean JavaDoc)
476         return "boolean";
477       else if (obj instanceof Number JavaDoc)
478         return "number";
479       else if (obj instanceof DOM)
480         return "RTF";
481       else if (obj instanceof DTMAxisIterator)
482         return "node-set";
483       else
484         return "unknown";
485     }
486
487     /**
488      * Implements the nodeset() extension function.
489      */

490     public static DTMAxisIterator nodesetF(Object JavaDoc obj) {
491     if (obj instanceof DOM) {
492        //final DOMAdapter adapter = (DOMAdapter) obj;
493
final DOM dom = (DOM)obj;
494        return new SingletonIterator(dom.getDocument(), true);
495     }
496         else if (obj instanceof DTMAxisIterator) {
497        return (DTMAxisIterator) obj;
498         }
499         else {
500         final String JavaDoc className = obj.getClass().getName();
501         runTimeError(DATA_CONVERSION_ERR, "node-set", className);
502         return null;
503         }
504     }
505
506     //-- Begin utility functions
507

508     private static boolean isWhiteSpace(char ch) {
509     return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
510     }
511
512     private static boolean compareStrings(String JavaDoc lstring, String JavaDoc rstring,
513                       int op, DOM dom) {
514     switch (op) {
515     case EQ:
516         return lstring.equals(rstring);
517
518     case NE:
519         return !lstring.equals(rstring);
520
521     case GT:
522         return numberF(lstring, dom) > numberF(rstring, dom);
523
524     case LT:
525         return numberF(lstring, dom) < numberF(rstring, dom);
526
527     case GE:
528         return numberF(lstring, dom) >= numberF(rstring, dom);
529
530     case LE:
531         return numberF(lstring, dom) <= numberF(rstring, dom);
532
533     default:
534         runTimeError(RUN_TIME_INTERNAL_ERR, "compare()");
535         return false;
536     }
537     }
538
539     /**
540      * Utility function: node-set/node-set compare.
541      */

542     public static boolean compare(DTMAxisIterator left, DTMAxisIterator right,
543                   int op, DOM dom) {
544     int lnode;
545     left.reset();
546     
547     while ((lnode = left.next()) != DTMAxisIterator.END) {
548         final String JavaDoc lvalue = dom.getStringValueX(lnode);
549         
550         int rnode;
551         right.reset();
552         while ((rnode = right.next()) != DTMAxisIterator.END) {
553                 // String value must be the same if both nodes are the same
554
if (lnode == rnode) {
555                     if (op == EQ) {
556                         return true;
557                     } else if (op == NE) {
558                         continue;
559                     }
560                 }
561         if (compareStrings(lvalue, dom.getStringValueX(rnode), op,
562                                    dom)) {
563             return true;
564         }
565         }
566     }
567     return false;
568     }
569
570     public static boolean compare(int node, DTMAxisIterator iterator,
571                   int op, DOM dom) {
572     //iterator.reset();
573

574     int rnode;
575     String JavaDoc value;
576
577     switch(op) {
578     case EQ:
579             rnode = iterator.next();
580             if (rnode != DTMAxisIterator.END) {
581             value = dom.getStringValueX(node);
582                 do {
583             if (node == rnode
584                           || value.equals(dom.getStringValueX(rnode))) {
585                        return true;
586                     }
587             } while ((rnode = iterator.next()) != DTMAxisIterator.END);
588             }
589         break;
590     case NE:
591             rnode = iterator.next();
592             if (rnode != DTMAxisIterator.END) {
593             value = dom.getStringValueX(node);
594                 do {
595             if (node != rnode
596                           && !value.equals(dom.getStringValueX(rnode))) {
597                         return true;
598                     }
599             } while ((rnode = iterator.next()) != DTMAxisIterator.END);
600             }
601         break;
602     case LT:
603         // Assume we're comparing document order here
604
while ((rnode = iterator.next()) != DTMAxisIterator.END) {
605         if (rnode > node) return true;
606         }
607         break;
608     case GT:
609         // Assume we're comparing document order here
610
while ((rnode = iterator.next()) != DTMAxisIterator.END) {
611         if (rnode < node) return true;
612         }
613         break;
614     }
615     return(false);
616     }
617
618     /**
619      * Utility function: node-set/number compare.
620      */

621     public static boolean compare(DTMAxisIterator left, final double rnumber,
622                   final int op, DOM dom) {
623     int node;
624     //left.reset();
625

626     switch (op) {
627     case EQ:
628         while ((node = left.next()) != DTMAxisIterator.END) {
629         if (numberF(dom.getStringValueX(node), dom) == rnumber)
630             return true;
631         }
632         break;
633
634     case NE:
635         while ((node = left.next()) != DTMAxisIterator.END) {
636         if (numberF(dom.getStringValueX(node), dom) != rnumber)
637             return true;
638         }
639         break;
640
641     case GT:
642         while ((node = left.next()) != DTMAxisIterator.END) {
643         if (numberF(dom.getStringValueX(node), dom) > rnumber)
644             return true;
645         }
646         break;
647
648     case LT:
649         while ((node = left.next()) != DTMAxisIterator.END) {
650         if (numberF(dom.getStringValueX(node), dom) < rnumber)
651             return true;
652         }
653         break;
654
655     case GE:
656         while ((node = left.next()) != DTMAxisIterator.END) {
657         if (numberF(dom.getStringValueX(node), dom) >= rnumber)
658             return true;
659         }
660         break;
661
662     case LE:
663         while ((node = left.next()) != DTMAxisIterator.END) {
664         if (numberF(dom.getStringValueX(node), dom) <= rnumber)
665             return true;
666         }
667         break;
668
669     default:
670         runTimeError(RUN_TIME_INTERNAL_ERR, "compare()");
671     }
672
673     return false;
674     }
675
676     /**
677      * Utility function: node-set/string comparison.
678      */

679     public static boolean compare(DTMAxisIterator left, final String JavaDoc rstring,
680                   int op, DOM dom) {
681     int node;
682     //left.reset();
683
while ((node = left.next()) != DTMAxisIterator.END) {
684         if (compareStrings(dom.getStringValueX(node), rstring, op, dom)) {
685         return true;
686         }
687     }
688     return false;
689     }
690
691
692     public static boolean compare(Object JavaDoc left, Object JavaDoc right,
693                   int op, DOM dom)
694     {
695     boolean result = false;
696     boolean hasSimpleArgs = hasSimpleType(left) && hasSimpleType(right);
697
698     if (op != EQ && op != NE) {
699         // If node-boolean comparison -> convert node to boolean
700
if (left instanceof Node || right instanceof Node) {
701         if (left instanceof Boolean JavaDoc) {
702             right = new Boolean JavaDoc(booleanF(right));
703             hasSimpleArgs = true;
704         }
705         if (right instanceof Boolean JavaDoc) {
706             left = new Boolean JavaDoc(booleanF(left));
707             hasSimpleArgs = true;
708         }
709         }
710
711         if (hasSimpleArgs) {
712         switch (op) {
713         case GT:
714             return numberF(left, dom) > numberF(right, dom);
715             
716         case LT:
717             return numberF(left, dom) < numberF(right, dom);
718             
719         case GE:
720             return numberF(left, dom) >= numberF(right, dom);
721             
722         case LE:
723             return numberF(left, dom) <= numberF(right, dom);
724             
725         default:
726             runTimeError(RUN_TIME_INTERNAL_ERR, "compare()");
727         }
728         }
729         // falls through
730
}
731
732     if (hasSimpleArgs) {
733         if (left instanceof Boolean JavaDoc || right instanceof Boolean JavaDoc) {
734         result = booleanF(left) == booleanF(right);
735         }
736         else if (left instanceof Double JavaDoc || right instanceof Double JavaDoc ||
737              left instanceof Integer JavaDoc || right instanceof Integer JavaDoc) {
738         result = numberF(left, dom) == numberF(right, dom);
739         }
740         else { // compare them as strings
741
result = stringF(left, dom).equals(stringF(right, dom));
742         }
743
744         if (op == Operators.NE) {
745         result = !result;
746         }
747     }
748     else {
749         if (left instanceof Node) {
750         left = new SingletonIterator(((Node)left).node);
751         }
752         if (right instanceof Node) {
753         right = new SingletonIterator(((Node)right).node);
754         }
755
756         if (hasSimpleType(left) ||
757         left instanceof DOM && right instanceof DTMAxisIterator) {
758         // swap operands
759
final Object JavaDoc temp = right; right = left; left = temp;
760         }
761
762         if (left instanceof DOM) {
763         if (right instanceof Boolean JavaDoc) {
764             result = ((Boolean JavaDoc)right).booleanValue();
765             return result == (op == Operators.EQ);
766         }
767
768         final String JavaDoc sleft = ((DOM)left).getStringValue();
769
770         if (right instanceof Number JavaDoc) {
771             result = ((Number JavaDoc)right).doubleValue() ==
772             stringToReal(sleft);
773         }
774         else if (right instanceof String JavaDoc) {
775             result = sleft.equals((String JavaDoc)right);
776         }
777         else if (right instanceof DOM) {
778             result = sleft.equals(((DOM)right).getStringValue());
779         }
780
781         if (op == Operators.NE) {
782             result = !result;
783         }
784         return result;
785         }
786
787         // Next, node-set/t for t in {real, string, node-set, result-tree}
788

789         DTMAxisIterator iter = ((DTMAxisIterator)left).reset();
790
791         if (right instanceof DTMAxisIterator) {
792         result = compare(iter, (DTMAxisIterator)right, op, dom);
793         }
794         else if (right instanceof String JavaDoc) {
795         result = compare(iter, (String JavaDoc)right, op, dom);
796         }
797         else if (right instanceof Number JavaDoc) {
798         final double temp = ((Number JavaDoc)right).doubleValue();
799         result = compare(iter, temp, op, dom);
800         }
801         else if (right instanceof Boolean JavaDoc) {
802         boolean temp = ((Boolean JavaDoc)right).booleanValue();
803         result = (iter.reset().next() != DTMAxisIterator.END) == temp;
804         }
805         else if (right instanceof DOM) {
806         result = compare(iter, ((DOM)right).getStringValue(),
807                  op, dom);
808         }
809         else if (right == null) {
810         return(false);
811         }
812         else {
813         final String JavaDoc className = right.getClass().getName();
814         runTimeError(INVALID_ARGUMENT_ERR, className, "compare()");
815         }
816     }
817     return result;
818     }
819
820     /**
821      * Utility function: used to test context node's language
822      */

823     public static boolean testLanguage(String JavaDoc testLang, DOM dom, int node) {
824     // language for context node (if any)
825
String JavaDoc nodeLang = dom.getLanguage(node);
826     if (nodeLang == null)
827         return(false);
828     else
829         nodeLang = nodeLang.toLowerCase();
830
831     // compare context node's language agains test language
832
testLang = testLang.toLowerCase();
833     if (testLang.length() == 2) {
834         return(nodeLang.startsWith(testLang));
835     }
836     else {
837         return(nodeLang.equals(testLang));
838     }
839     }
840
841     private static boolean hasSimpleType(Object JavaDoc obj) {
842     return obj instanceof Boolean JavaDoc || obj instanceof Double JavaDoc ||
843         obj instanceof Integer JavaDoc || obj instanceof String JavaDoc ||
844         obj instanceof Node || obj instanceof DOM;
845     }
846
847     /**
848      * Utility function: used in StringType to convert a string to a real.
849      */

850     public static double stringToReal(String JavaDoc s) {
851     try {
852         return Double.valueOf(s).doubleValue();
853     }
854     catch (NumberFormatException JavaDoc e) {
855         return Double.NaN;
856     }
857     }
858
859     /**
860      * Utility function: used in StringType to convert a string to an int.
861      */

862     public static int stringToInt(String JavaDoc s) {
863     try {
864         return Integer.parseInt(s);
865     }
866     catch (NumberFormatException JavaDoc e) {
867         return(-1); // ???
868
}
869     }
870
871     private static final int DOUBLE_FRACTION_DIGITS = 340;
872     private static final double lowerBounds = 0.001;
873     private static final double upperBounds = 10000000;
874     private static DecimalFormat JavaDoc defaultFormatter;
875     private static String JavaDoc defaultPattern = "";
876
877     static {
878     NumberFormat JavaDoc f = NumberFormat.getInstance(Locale.getDefault());
879     defaultFormatter = (f instanceof DecimalFormat JavaDoc) ?
880         (DecimalFormat JavaDoc) f : new DecimalFormat JavaDoc();
881     // Set max fraction digits so that truncation does not occur. Setting
882
// the max to Integer.MAX_VALUE may cause problems with some JDK's.
883
defaultFormatter.setMaximumFractionDigits(DOUBLE_FRACTION_DIGITS);
884         defaultFormatter.setMinimumFractionDigits(0);
885         defaultFormatter.setMinimumIntegerDigits(1);
886         defaultFormatter.setGroupingUsed(false);
887     }
888
889     /**
890      * Utility function: used in RealType to convert a real to a string.
891      * Removes the decimal if null.
892      */

893     public static String JavaDoc realToString(double d) {
894     final double m = Math.abs(d);
895     if ((m >= lowerBounds) && (m < upperBounds)) {
896         final String JavaDoc result = Double.toString(d);
897         final int length = result.length();
898         // Remove leading zeros.
899
if ((result.charAt(length-2) == '.') &&
900         (result.charAt(length-1) == '0'))
901         return result.substring(0, length-2);
902         else
903         return result;
904     }
905     else {
906         if (Double.isNaN(d) || Double.isInfinite(d))
907         return(Double.toString(d));
908         return formatNumber(d, defaultPattern, defaultFormatter);
909     }
910     }
911
912     /**
913      * Utility function: used in RealType to convert a real to an integer
914      */

915     public static int realToInt(double d) {
916     return (int)d;
917     }
918
919     /**
920      * Utility function: used to format/adjust a double to a string. The
921      * DecimalFormat object comes from the 'formatSymbols' hashtable in
922      * AbstractTranslet.
923      */

924     private static FieldPosition JavaDoc _fieldPosition = new FieldPosition JavaDoc(0);
925
926     public static String JavaDoc formatNumber(double number, String JavaDoc pattern,
927                       DecimalFormat JavaDoc formatter) {
928         // bugzilla fix 12813
929
if (formatter == null) {
930         formatter = defaultFormatter;
931     }
932     try {
933         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
934         if (pattern != defaultPattern) {
935         formatter.applyLocalizedPattern(pattern);
936         }
937             formatter.format(number, result, _fieldPosition);
938         return result.toString();
939     }
940     catch (IllegalArgumentException JavaDoc e) {
941         runTimeError(FORMAT_NUMBER_ERR, Double.toString(number), pattern);
942         return(EMPTYSTRING);
943     }
944     }
945     
946     /**
947      * Utility function: used to convert references to node-sets. If the
948      * obj is an instanceof Node then create a singleton iterator.
949      */

950     public static DTMAxisIterator referenceToNodeSet(Object JavaDoc obj) {
951     // Convert var/param -> node
952
if (obj instanceof Node) {
953         return(new SingletonIterator(((Node)obj).node));
954     }
955     // Convert var/param -> node-set
956
else if (obj instanceof DTMAxisIterator) {
957         return(((DTMAxisIterator)obj).cloneIterator());
958     }
959     else {
960         final String JavaDoc className = obj.getClass().getName();
961         runTimeError(DATA_CONVERSION_ERR, className, "node-set");
962         return null;
963     }
964     }
965     
966     /**
967      * Utility function: used to convert reference to org.w3c.dom.NodeList.
968      */

969     public static NodeList JavaDoc referenceToNodeList(Object JavaDoc obj, DOM dom) {
970         if (obj instanceof Node || obj instanceof DTMAxisIterator) {
971             DTMAxisIterator iter = referenceToNodeSet(obj);
972             return dom.makeNodeList(iter);
973         }
974         else if (obj instanceof DOM) {
975           dom = (DOM)obj;
976           return dom.makeNodeList(DTMDefaultBase.ROOTNODE);
977         }
978     else {
979         final String JavaDoc className = obj.getClass().getName();
980         runTimeError(DATA_CONVERSION_ERR, className,
981                 "org.w3c.dom.NodeList");
982         return null;
983     }
984     }
985
986     /**
987      * Utility function: used to convert reference to org.w3c.dom.Node.
988      */

989     public static org.w3c.dom.Node JavaDoc referenceToNode(Object JavaDoc obj, DOM dom) {
990         if (obj instanceof Node || obj instanceof DTMAxisIterator) {
991             DTMAxisIterator iter = referenceToNodeSet(obj);
992             return dom.makeNode(iter);
993         }
994         else if (obj instanceof DOM) {
995           dom = (DOM)obj;
996           DTMAxisIterator iter = dom.getChildren(DTMDefaultBase.ROOTNODE);
997           return dom.makeNode(iter);
998         }
999     else {
1000        final String JavaDoc className = obj.getClass().getName();
1001        runTimeError(DATA_CONVERSION_ERR, className, "org.w3c.dom.Node");
1002        return null;
1003    }
1004    }
1005   
1006    /**
1007     * Utility function: used to convert reference to long.
1008     */

1009    public static long referenceToLong(Object JavaDoc obj) {
1010        if (obj instanceof Number JavaDoc) {
1011            return ((Number JavaDoc) obj).longValue(); // handles Integer and Double
1012
}
1013        else {
1014        final String JavaDoc className = obj.getClass().getName();
1015        runTimeError(DATA_CONVERSION_ERR, className, Long.TYPE);
1016        return 0;
1017        }
1018    }
1019            
1020    /**
1021     * Utility function: used to convert reference to double.
1022     */

1023    public static double referenceToDouble(Object JavaDoc obj) {
1024        if (obj instanceof Number JavaDoc) {
1025            return ((Number JavaDoc) obj).doubleValue(); // handles Integer and Double
1026
}
1027        else {
1028        final String JavaDoc className = obj.getClass().getName();
1029        runTimeError(DATA_CONVERSION_ERR, className, Double.TYPE);
1030        return 0;
1031        }
1032    }
1033
1034    /**
1035     * Utility function: used to convert reference to boolean.
1036     */

1037    public static boolean referenceToBoolean(Object JavaDoc obj) {
1038        if (obj instanceof Boolean JavaDoc) {
1039            return ((Boolean JavaDoc) obj).booleanValue();
1040        }
1041        else {
1042        final String JavaDoc className = obj.getClass().getName();
1043        runTimeError(DATA_CONVERSION_ERR, className, Boolean.TYPE);
1044        return false;
1045        }
1046    }
1047
1048    /**
1049     * Utility function: used to convert reference to String.
1050     */

1051    public static String JavaDoc referenceToString(Object JavaDoc obj, DOM dom) {
1052        if (obj instanceof String JavaDoc) {
1053            return (String JavaDoc) obj;
1054        }
1055        else if (obj instanceof DTMAxisIterator) {
1056        return dom.getStringValueX(((DTMAxisIterator)obj).reset().next());
1057    }
1058    else if (obj instanceof Node) {
1059        return dom.getStringValueX(((Node)obj).node);
1060    }
1061    else if (obj instanceof DOM) {
1062        return ((DOM) obj).getStringValue();
1063    }
1064        else {
1065        final String JavaDoc className = obj.getClass().getName();
1066        runTimeError(DATA_CONVERSION_ERR, className, String JavaDoc.class);
1067        return null;
1068        }
1069    }
1070
1071    /**
1072     * Utility function used to convert a w3c Node into an internal DOM iterator.
1073     */

1074    public static DTMAxisIterator node2Iterator(org.w3c.dom.Node JavaDoc node,
1075    Translet translet, DOM dom)
1076    {
1077        final org.w3c.dom.Node JavaDoc inNode = node;
1078        // Create a dummy NodeList which only contains the given node to make
1079
// use of the nodeList2Iterator() interface.
1080
org.w3c.dom.NodeList JavaDoc nodelist = new org.w3c.dom.NodeList JavaDoc() {
1081            public int getLength() {
1082                return 1;
1083            }
1084            
1085            public org.w3c.dom.Node JavaDoc item(int index) {
1086                if (index == 0)
1087                    return inNode;
1088                else
1089                    return null;
1090            }
1091        };
1092        
1093        return nodeList2Iterator(nodelist, translet, dom);
1094    }
1095    
1096    /**
1097     * Utility function used to copy a node list to be under a parent node.
1098     */

1099    private static void copyNodes(org.w3c.dom.NodeList JavaDoc nodeList,
1100    org.w3c.dom.Document JavaDoc doc, org.w3c.dom.Node JavaDoc parent)
1101    {
1102        final int size = nodeList.getLength();
1103
1104          // copy Nodes from NodeList into new w3c DOM
1105
for (int i = 0; i < size; i++)
1106        {
1107            org.w3c.dom.Node JavaDoc curr = nodeList.item(i);
1108            int nodeType = curr.getNodeType();
1109            String JavaDoc value = null;
1110            try {
1111                value = curr.getNodeValue();
1112            } catch (DOMException JavaDoc ex) {
1113                runTimeError(RUN_TIME_INTERNAL_ERR, ex.getMessage());
1114                return;
1115            }
1116            
1117            String JavaDoc nodeName = curr.getNodeName();
1118            org.w3c.dom.Node JavaDoc newNode = null;
1119            switch (nodeType){
1120                case org.w3c.dom.Node.ATTRIBUTE_NODE:
1121                     newNode = doc.createAttributeNS(curr.getNamespaceURI(),
1122            nodeName);
1123                     break;
1124                case org.w3c.dom.Node.CDATA_SECTION_NODE:
1125                     newNode = doc.createCDATASection(value);
1126                     break;
1127                case org.w3c.dom.Node.COMMENT_NODE:
1128                     newNode = doc.createComment(value);
1129                     break;
1130                case org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE:
1131                     newNode = doc.createDocumentFragment();
1132                     break;
1133                case org.w3c.dom.Node.DOCUMENT_NODE:
1134                     newNode = doc.createElementNS(null, "__document__");
1135                     copyNodes(curr.getChildNodes(), doc, newNode);
1136                     break;
1137                case org.w3c.dom.Node.DOCUMENT_TYPE_NODE:
1138                     // nothing?
1139
break;
1140                case org.w3c.dom.Node.ELEMENT_NODE:
1141                     // For Element node, also copy the children and the
1142
// attributes.
1143
org.w3c.dom.Element JavaDoc element = doc.createElementNS(
1144            curr.getNamespaceURI(), nodeName);
1145                     if (curr.hasAttributes())
1146                     {
1147                       org.w3c.dom.NamedNodeMap JavaDoc attributes = curr.getAttributes();
1148                       for (int k = 0; k < attributes.getLength(); k++) {
1149                         org.w3c.dom.Node JavaDoc attr = attributes.item(k);
1150                         element.setAttributeNS(attr.getNamespaceURI(),
1151                                 attr.getNodeName(), attr.getNodeValue());
1152                       }
1153                     }
1154                     copyNodes(curr.getChildNodes(), doc, element);
1155                     newNode = element;
1156                     break;
1157                case org.w3c.dom.Node.ENTITY_NODE:
1158                     // nothing ?
1159
break;
1160                case org.w3c.dom.Node.ENTITY_REFERENCE_NODE:
1161                     newNode = doc.createEntityReference(nodeName);
1162                     break;
1163                case org.w3c.dom.Node.NOTATION_NODE:
1164                     // nothing ?
1165
break;
1166                case org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE:
1167                     newNode = doc.createProcessingInstruction(nodeName,
1168                        value);
1169                     break;
1170                case org.w3c.dom.Node.TEXT_NODE:
1171                     newNode = doc.createTextNode(value);
1172                     break;
1173            }
1174            try {
1175                parent.appendChild(newNode);
1176            } catch (DOMException JavaDoc e) {
1177                runTimeError(RUN_TIME_INTERNAL_ERR, e.getMessage());
1178                return;
1179            }
1180        }
1181    }
1182
1183    /**
1184     * Utility function used to convert a w3c NodeList into a internal
1185     * DOM iterator.
1186     */

1187    public static DTMAxisIterator nodeList2Iterator(
1188                                        org.w3c.dom.NodeList JavaDoc nodeList,
1189                                        Translet translet, DOM dom)
1190    {
1191    // w3c NodeList -> w3c DOM
1192
Document JavaDoc doc = null;
1193    try {
1194           doc = ((AbstractTranslet) translet).newDocument("", "__top__");
1195    } catch (javax.xml.parsers.ParserConfigurationException JavaDoc e) {
1196        runTimeError(RUN_TIME_INTERNAL_ERR, e.getMessage());
1197            return null;
1198    }
1199    
1200        copyNodes(nodeList, doc, doc.getDocumentElement());
1201
1202        // w3cDOM -> DTM -> DOMImpl
1203
if (dom instanceof MultiDOM) {
1204            final MultiDOM multiDOM = (MultiDOM) dom;
1205
1206        DTMDefaultBase dtm = (DTMDefaultBase)((DOMAdapter)multiDOM.getMain()).getDOMImpl();
1207        DTMManager dtmManager = dtm.getManager();
1208        
1209        DOM idom = (DOM)dtmManager.getDTM(new DOMSource JavaDoc(doc), false,
1210                          null, true, false);
1211        // Create DOMAdapter and register with MultiDOM
1212
DOMAdapter domAdapter = new DOMAdapter(idom,
1213                translet.getNamesArray(),
1214                translet.getUrisArray(),
1215                translet.getTypesArray(),
1216        translet.getNamespaceArray());
1217            multiDOM.addDOMAdapter(domAdapter);
1218
1219        DTMAxisIterator iter1 = idom.getAxisIterator(Axis.CHILD);
1220        DTMAxisIterator iter2 = idom.getAxisIterator(Axis.CHILD);
1221            DTMAxisIterator iter = new AbsoluteIterator(
1222                new StepIterator(iter1, iter2));
1223
1224        iter.setStartNode(DTMDefaultBase.ROOTNODE);
1225        return iter;
1226    }
1227        else {
1228        runTimeError(RUN_TIME_INTERNAL_ERR, "nodeList2Iterator()");
1229        return null;
1230        }
1231    }
1232
1233    /**
1234     * Utility function used to convert references to DOMs.
1235     */

1236    public static DOM referenceToResultTree(Object JavaDoc obj) {
1237    try {
1238        return ((DOM) obj);
1239    }
1240    catch (IllegalArgumentException JavaDoc e) {
1241        final String JavaDoc className = obj.getClass().getName();
1242        runTimeError(DATA_CONVERSION_ERR, "reference", className);
1243        return null;
1244    }
1245    }
1246
1247    /**
1248     * Utility function: used with nth position filters to convert a sequence
1249     * of nodes to just one single node (the one at position n).
1250     */

1251    public static DTMAxisIterator getSingleNode(DTMAxisIterator iterator) {
1252    int node = iterator.next();
1253    return(new SingletonIterator(node));
1254    }
1255
1256    /**
1257     * Utility function: used in xsl:copy.
1258     */

1259    private static char[] _characterArray = new char[32];
1260
1261    public static void copy(Object JavaDoc obj,
1262                SerializationHandler handler,
1263                int node,
1264                DOM dom) {
1265    try {
1266        if (obj instanceof DTMAxisIterator)
1267      {
1268        DTMAxisIterator iter = (DTMAxisIterator) obj;
1269        dom.copy(iter.reset(), handler);
1270        }
1271        else if (obj instanceof Node) {
1272        dom.copy(((Node) obj).node, handler);
1273        }
1274        else if (obj instanceof DOM) {
1275        //((DOM)obj).copy(((com.sun.org.apache.xml.internal.dtm.ref.DTMDefaultBase)((DOMAdapter)obj).getDOMImpl()).getDocument(), handler);
1276
DOM newDom = (DOM)obj;
1277        newDom.copy(newDom.getDocument(), handler);
1278        }
1279        else {
1280        String JavaDoc string = obj.toString(); // or call stringF()
1281
final int length = string.length();
1282        if (length > _characterArray.length)
1283            _characterArray = new char[length];
1284        string.getChars(0, length, _characterArray, 0);
1285        handler.characters(_characterArray, 0, length);
1286        }
1287    }
1288    catch (SAXException JavaDoc e) {
1289        runTimeError(RUN_TIME_COPY_ERR);
1290    }
1291    }
1292    
1293    /**
1294     * Utility function to check if xsl:attribute has a valid qname
1295     * This method should only be invoked if the name attribute is an AVT
1296     */

1297    public static void checkAttribQName(String JavaDoc name) {
1298        final int firstOccur = name.indexOf(":");
1299        final int lastOccur = name.lastIndexOf(":");
1300        final String JavaDoc localName = name.substring(lastOccur + 1);
1301        
1302        if (firstOccur > 0) {
1303            final String JavaDoc newPrefix = name.substring(0, firstOccur);
1304        
1305            if (firstOccur != lastOccur) {
1306               final String JavaDoc oriPrefix = name.substring(firstOccur+1, lastOccur);
1307                if (!XMLChar.isValidNCName(oriPrefix)) {
1308                    // even though the orignal prefix is ignored, it should still get checked for valid NCName
1309
runTimeError(INVALID_QNAME_ERR,oriPrefix+":"+localName);
1310                }
1311            }
1312            
1313            // prefix must be a valid NCName
1314
if (!XMLChar.isValidNCName(newPrefix)) {
1315                runTimeError(INVALID_QNAME_ERR,newPrefix+":"+localName);
1316            }
1317        }
1318                
1319        // local name must be a valid NCName and must not be XMLNS
1320
if ((!XMLChar.isValidNCName(localName))||(localName.equals(Constants.XMLNS_PREFIX))) {
1321            runTimeError(INVALID_QNAME_ERR,localName);
1322        }
1323    }
1324    
1325    /**
1326     * Utility function to check if a name is a valid ncname
1327     * This method should only be invoked if the attribute value is an AVT
1328     */

1329    public static void checkNCName(String JavaDoc name) {
1330        if (!XMLChar.isValidNCName(name)) {
1331            runTimeError(INVALID_NCNAME_ERR,name);
1332        }
1333    }
1334
1335    /**
1336     * Utility function to check if a name is a valid qname
1337     * This method should only be invoked if the attribute value is an AVT
1338     */

1339    public static void checkQName(String JavaDoc name) {
1340        if (!XMLChar.isValidQName(name)) {
1341            runTimeError(INVALID_QNAME_ERR,name);
1342        }
1343    }
1344    
1345    /**
1346     * Utility function for the implementation of xsl:element.
1347     */

1348    public static String JavaDoc startXslElement(String JavaDoc qname, String JavaDoc namespace,
1349    SerializationHandler handler, DOM dom, int node)
1350    {
1351        try {
1352            // Get prefix from qname
1353
String JavaDoc prefix;
1354            final int index = qname.indexOf(':');
1355            
1356            if (index > 0) {
1357                prefix = qname.substring(0, index);
1358                
1359                // Handle case when prefix is not known at compile time
1360
if (namespace == null || namespace.length() == 0) {
1361                    try {
1362                        // not sure if this line of code ever works
1363
namespace = dom.lookupNamespace(node, prefix);
1364                    }
1365                    catch(RuntimeException JavaDoc e) {
1366                        handler.flushPending(); // need to flush or else can't get namespacemappings
1367
NamespaceMappings nm = handler.getNamespaceMappings();
1368                        namespace = nm.lookupNamespace(prefix);
1369                        if (namespace == null) {
1370                            runTimeError(NAMESPACE_PREFIX_ERR,prefix);
1371                        }
1372                    }
1373                }
1374                
1375                handler.startElement(namespace, qname.substring(index+1),
1376                                         qname);
1377                handler.namespaceAfterStartElement(prefix, namespace);
1378            }
1379            else {
1380                // Need to generate a prefix?
1381
if (namespace != null && namespace.length() > 0) {
1382                    prefix = generatePrefix();
1383                    qname = prefix + ':' + qname;
1384                    handler.startElement(namespace, qname, qname);
1385                    handler.namespaceAfterStartElement(prefix, namespace);
1386                }
1387                else {
1388                    handler.startElement(null, null, qname);
1389                }
1390            }
1391        }
1392        catch (SAXException JavaDoc e) {
1393            throw new RuntimeException JavaDoc(e.getMessage());
1394        }
1395    
1396        return qname;
1397    }
1398
1399    /**
1400     * This function is used in the execution of xsl:element
1401     */

1402    public static String JavaDoc getPrefix(String JavaDoc qname) {
1403    final int index = qname.indexOf(':');
1404    return (index > 0) ? qname.substring(0, index) : null;
1405    }
1406
1407    /**
1408     * This function is used in the execution of xsl:element
1409     */

1410    private static int prefixIndex = 0; // not thread safe!!
1411
public static String JavaDoc generatePrefix() {
1412    return ("ns" + prefixIndex++);
1413    }
1414
1415    public static final String JavaDoc RUN_TIME_INTERNAL_ERR =
1416                                           "RUN_TIME_INTERNAL_ERR";
1417    public static final String JavaDoc RUN_TIME_COPY_ERR =
1418                                           "RUN_TIME_COPY_ERR";
1419    public static final String JavaDoc DATA_CONVERSION_ERR =
1420                                           "DATA_CONVERSION_ERR";
1421    public static final String JavaDoc EXTERNAL_FUNC_ERR =
1422                                           "EXTERNAL_FUNC_ERR";
1423    public static final String JavaDoc EQUALITY_EXPR_ERR =
1424                                           "EQUALITY_EXPR_ERR";
1425    public static final String JavaDoc INVALID_ARGUMENT_ERR =
1426                                           "INVALID_ARGUMENT_ERR";
1427    public static final String JavaDoc FORMAT_NUMBER_ERR =
1428                                           "FORMAT_NUMBER_ERR";
1429    public static final String JavaDoc ITERATOR_CLONE_ERR =
1430                                           "ITERATOR_CLONE_ERR";
1431    public static final String JavaDoc AXIS_SUPPORT_ERR =
1432                                           "AXIS_SUPPORT_ERR";
1433    public static final String JavaDoc TYPED_AXIS_SUPPORT_ERR =
1434                                           "TYPED_AXIS_SUPPORT_ERR";
1435    public static final String JavaDoc STRAY_ATTRIBUTE_ERR =
1436                                           "STRAY_ATTRIBUTE_ERR";
1437    public static final String JavaDoc STRAY_NAMESPACE_ERR =
1438                                           "STRAY_NAMESPACE_ERR";
1439    public static final String JavaDoc NAMESPACE_PREFIX_ERR =
1440                                           "NAMESPACE_PREFIX_ERR";
1441    public static final String JavaDoc DOM_ADAPTER_INIT_ERR =
1442                                           "DOM_ADAPTER_INIT_ERR";
1443    public static final String JavaDoc PARSER_DTD_SUPPORT_ERR =
1444                                           "PARSER_DTD_SUPPORT_ERR";
1445    public static final String JavaDoc NAMESPACES_SUPPORT_ERR =
1446                                           "NAMESPACES_SUPPORT_ERR";
1447    public static final String JavaDoc CANT_RESOLVE_RELATIVE_URI_ERR =
1448                                           "CANT_RESOLVE_RELATIVE_URI_ERR";
1449    public static final String JavaDoc UNSUPPORTED_XSL_ERR =
1450                                           "UNSUPPORTED_XSL_ERR";
1451    public static final String JavaDoc UNSUPPORTED_EXT_ERR =
1452                                           "UNSUPPORTED_EXT_ERR";
1453    public static final String JavaDoc UNKNOWN_TRANSLET_VERSION_ERR =
1454                                           "UNKNOWN_TRANSLET_VERSION_ERR";
1455    public static final String JavaDoc INVALID_QNAME_ERR = "INVALID_QNAME_ERR";
1456    public static final String JavaDoc INVALID_NCNAME_ERR = "INVALID_NCNAME_ERR";
1457    public static final String JavaDoc UNALLOWED_EXTENSION_FUNCTION_ERR = "UNALLOWED_EXTENSION_FUNCTION_ERR";
1458    public static final String JavaDoc UNALLOWED_EXTENSION_ELEMENT_ERR = "UNALLOWED_EXTENSION_ELEMENT_ERR";
1459
1460    // All error messages are localized and are stored in resource bundles.
1461
protected static ResourceBundle JavaDoc m_bundle;
1462    
1463    public final static String JavaDoc ERROR_MESSAGES_KEY = "error-messages";
1464
1465    static {
1466    String JavaDoc resource = "com.sun.org.apache.xalan.internal.xsltc.runtime.ErrorMessages";
1467    m_bundle = ResourceBundle.getBundle(resource);
1468    }
1469
1470    /**
1471     * Print a run-time error message.
1472     */

1473    public static void runTimeError(String JavaDoc code) {
1474    throw new RuntimeException JavaDoc(m_bundle.getString(code));
1475    }
1476
1477    public static void runTimeError(String JavaDoc code, Object JavaDoc[] args) {
1478    final String JavaDoc message = MessageFormat.format(m_bundle.getString(code),
1479                                                    args);
1480    throw new RuntimeException JavaDoc(message);
1481    }
1482
1483    public static void runTimeError(String JavaDoc code, Object JavaDoc arg0) {
1484    runTimeError(code, new Object JavaDoc[]{ arg0 } );
1485    }
1486
1487    public static void runTimeError(String JavaDoc code, Object JavaDoc arg0, Object JavaDoc arg1) {
1488    runTimeError(code, new Object JavaDoc[]{ arg0, arg1 } );
1489    }
1490
1491    public static void consoleOutput(String JavaDoc msg) {
1492    System.out.println(msg);
1493    }
1494
1495    /**
1496     * Replace a certain character in a string with a new substring.
1497     */

1498    public static String JavaDoc replace(String JavaDoc base, char ch, String JavaDoc str) {
1499    return (base.indexOf(ch) < 0) ? base :
1500        replace(base, String.valueOf(ch), new String JavaDoc[] { str });
1501    }
1502
1503    public static String JavaDoc replace(String JavaDoc base, String JavaDoc delim, String JavaDoc[] str) {
1504    final int len = base.length();
1505    final StringBuffer JavaDoc result = new StringBuffer JavaDoc();
1506
1507    for (int i = 0; i < len; i++) {
1508        final char ch = base.charAt(i);
1509        final int k = delim.indexOf(ch);
1510
1511        if (k >= 0) {
1512        result.append(str[k]);
1513        }
1514        else {
1515        result.append(ch);
1516        }
1517    }
1518    return result.toString();
1519    }
1520
1521
1522    /**
1523     * Utility method to allow setting parameters of the form
1524     * {namespaceuri}localName
1525     * which get mapped to an instance variable in the class
1526     * Hence a parameter of the form "{http://foo.bar}xyz"
1527     * will be replaced with the corresponding values
1528     * by the BasisLibrary's utility method mapQNametoJavaName
1529     * and thus get mapped to legal java variable names
1530     */

1531    public static String JavaDoc mapQNameToJavaName (String JavaDoc base ) {
1532       return replace(base, ".-:/{}?#%*",
1533                      new String JavaDoc[] { "$dot$", "$dash$" ,"$colon$", "$slash$",
1534                                     "","$colon$","$ques$","$hash$","$per$",
1535                                     "$aster$"});
1536
1537    }
1538
1539    //-- End utility functions
1540
}
1541
Popular Tags