KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > xpath > objects > XString


1 /*
2  * Copyright 1999-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: XString.java,v 1.14 2004/02/17 04:34:38 minchau Exp $
18  */

19 package org.apache.xpath.objects;
20
21 import java.util.Locale JavaDoc;
22
23 import org.apache.xml.dtm.DTM;
24 import org.apache.xml.utils.XMLCharacterRecognizer;
25 import org.apache.xml.utils.XMLString;
26 import org.apache.xml.utils.XMLStringFactory;
27 import org.apache.xpath.ExpressionOwner;
28 import org.apache.xpath.XPathContext;
29 import org.apache.xpath.XPathVisitor;
30
31 /**
32  * This class represents an XPath string object, and is capable of
33  * converting the string to other types, such as a number.
34  * @xsl.usage general
35  */

36 public class XString extends XObject implements XMLString
37 {
38
39   /** Empty string XString object */
40   public static XString EMPTYSTRING = new XString("");
41
42   /**
43    * Construct a XString object. This constructor exists for derived classes.
44    *
45    * @param val String object this will wrap.
46    */

47   protected XString(Object JavaDoc val)
48   {
49     super(val);
50   }
51
52   /**
53    * Construct a XNodeSet object.
54    *
55    * @param val String object this will wrap.
56    */

57   public XString(String JavaDoc val)
58   {
59     super(val);
60   }
61
62   /**
63    * Tell that this is a CLASS_STRING.
64    *
65    * @return type CLASS_STRING
66    */

67   public int getType()
68   {
69     return CLASS_STRING;
70   }
71
72   /**
73    * Given a request type, return the equivalent string.
74    * For diagnostic purposes.
75    *
76    * @return type string "#STRING"
77    */

78   public String JavaDoc getTypeString()
79   {
80     return "#STRING";
81   }
82
83   /**
84    * Tell if this object contains a java String object.
85    *
86    * @return true if this XMLString can return a string without creating one.
87    */

88   public boolean hasString()
89   {
90     return true;
91   }
92
93   /**
94    * Cast result object to a number.
95    *
96    * @return 0.0 if this string is null, numeric value of this string
97    * or NaN
98    */

99   public double num()
100   {
101     return toDouble();
102   }
103
104   /**
105    * Convert a string to a double -- Allowed input is in fixed
106    * notation ddd.fff.
107    *
108    * @return A double value representation of the string, or return Double.NaN
109    * if the string can not be converted.
110    */

111   public double toDouble()
112   {
113     int end = length();
114     
115     if(0 == end)
116       return Double.NaN;
117
118     double result = 0.0;
119     int start = 0;
120     int punctPos = end-1;
121
122     // Scan to first whitespace character.
123
for (int i = start; i < end; i++)
124     {
125       char c = charAt(i);
126
127       if (!XMLCharacterRecognizer.isWhiteSpace(c))
128       {
129         break;
130       }
131       else
132         start++;
133     }
134
135     double sign = 1.0;
136
137     if (start < end && charAt(start) == '-')
138     {
139       sign = -1.0;
140
141       start++;
142     }
143
144     int digitsFound = 0;
145
146     for (int i = start; i < end; i++) // parse the string from left to right converting the integer part
147
{
148       char c = charAt(i);
149
150       if (c != '.')
151       {
152         if (XMLCharacterRecognizer.isWhiteSpace(c))
153           break;
154         else if (Character.isDigit(c))
155         {
156           result = result * 10.0 + (c - 0x30);
157
158           digitsFound++;
159         }
160         else
161         {
162           return Double.NaN;
163         }
164       }
165       else
166       {
167         punctPos = i;
168
169         break;
170       }
171     }
172
173     if (charAt(punctPos) == '.') // parse the string from the end to the '.' converting the fractional part
174
{
175       double fractPart = 0.0;
176
177       for (int i = end - 1; i > punctPos; i--)
178       {
179         char c = charAt(i);
180
181         if (XMLCharacterRecognizer.isWhiteSpace(c))
182           break;
183         else if (Character.isDigit(c))
184         {
185           fractPart = fractPart / 10.0 + (c - 0x30);
186
187           digitsFound++;
188         }
189         else
190         {
191           return Double.NaN;
192         }
193       }
194
195       result += fractPart / 10.0;
196     }
197
198     if (0 == digitsFound)
199       return Double.NaN;
200
201     return result * sign;
202   }
203
204   /**
205    * Cast result object to a boolean.
206    *
207    * @return True if the length of this string object is greater
208    * than 0.
209    */

210   public boolean bool()
211   {
212     return str().length() > 0;
213   }
214
215   /**
216    * Cast result object to a string.
217    *
218    * @return The string this wraps or the empty string if null
219    */

220   public XMLString xstr()
221   {
222     return this;
223   }
224
225   /**
226    * Cast result object to a string.
227    *
228    * @return The string this wraps or the empty string if null
229    */

230   public String JavaDoc str()
231   {
232     return (null != m_obj) ? ((String JavaDoc) m_obj) : "";
233   }
234
235   /**
236    * Cast result object to a result tree fragment.
237    *
238    * @param support Xpath context to use for the conversion
239    *
240    * @return A document fragment with this string as a child node
241    */

242   public int rtf(XPathContext support)
243   {
244
245     DTM frag = support.createDocumentFragment();
246
247     frag.appendTextChild(str());
248
249     return frag.getDocument();
250   }
251
252   /**
253    * Directly call the
254    * characters method on the passed ContentHandler for the
255    * string-value. Multiple calls to the
256    * ContentHandler's characters methods may well occur for a single call to
257    * this method.
258    *
259    * @param ch A non-null reference to a ContentHandler.
260    *
261    * @throws org.xml.sax.SAXException
262    */

263   public void dispatchCharactersEvents(org.xml.sax.ContentHandler JavaDoc ch)
264           throws org.xml.sax.SAXException JavaDoc
265   {
266
267     String JavaDoc str = str();
268
269     ch.characters(str.toCharArray(), 0, str.length());
270   }
271
272   /**
273    * Directly call the
274    * comment method on the passed LexicalHandler for the
275    * string-value.
276    *
277    * @param lh A non-null reference to a LexicalHandler.
278    *
279    * @throws org.xml.sax.SAXException
280    */

281   public void dispatchAsComment(org.xml.sax.ext.LexicalHandler JavaDoc lh)
282           throws org.xml.sax.SAXException JavaDoc
283   {
284
285     String JavaDoc str = str();
286
287     lh.comment(str.toCharArray(), 0, str.length());
288   }
289
290   /**
291    * Returns the length of this string.
292    *
293    * @return the length of the sequence of characters represented by this
294    * object.
295    */

296   public int length()
297   {
298     return str().length();
299   }
300
301   /**
302    * Returns the character at the specified index. An index ranges
303    * from <code>0</code> to <code>length() - 1</code>. The first character
304    * of the sequence is at index <code>0</code>, the next at index
305    * <code>1</code>, and so on, as for array indexing.
306    *
307    * @param index the index of the character.
308    * @return the character at the specified index of this string.
309    * The first character is at index <code>0</code>.
310    * @exception IndexOutOfBoundsException if the <code>index</code>
311    * argument is negative or not less than the length of this
312    * string.
313    */

314   public char charAt(int index)
315   {
316     return str().charAt(index);
317   }
318
319   /**
320    * Copies characters from this string into the destination character
321    * array.
322    *
323    * @param srcBegin index of the first character in the string
324    * to copy.
325    * @param srcEnd index after the last character in the string
326    * to copy.
327    * @param dst the destination array.
328    * @param dstBegin the start offset in the destination array.
329    * @exception IndexOutOfBoundsException If any of the following
330    * is true:
331    * <ul><li><code>srcBegin</code> is negative.
332    * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
333    * <li><code>srcEnd</code> is greater than the length of this
334    * string
335    * <li><code>dstBegin</code> is negative
336    * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
337    * <code>dst.length</code></ul>
338    * @exception NullPointerException if <code>dst</code> is <code>null</code>
339    */

340   public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
341   {
342     str().getChars(srcBegin, srcEnd, dst, dstBegin);
343   }
344
345   /**
346    * Tell if two objects are functionally equal.
347    *
348    * @param obj2 Object to compare this to
349    *
350    * @return true if the two objects are equal
351    *
352    * @throws javax.xml.transform.TransformerException
353    */

354   public boolean equals(XObject obj2)
355   {
356
357     // In order to handle the 'all' semantics of
358
// nodeset comparisons, we always call the
359
// nodeset function.
360
int t = obj2.getType();
361     try
362     {
363         if (XObject.CLASS_NODESET == t)
364           return obj2.equals(this);
365         // If at least one object to be compared is a boolean, then each object
366
// to be compared is converted to a boolean as if by applying the
367
// boolean function.
368
else if(XObject.CLASS_BOOLEAN == t)
369             return obj2.bool() == bool();
370         // Otherwise, if at least one object to be compared is a number, then each object
371
// to be compared is converted to a number as if by applying the number function.
372
else if(XObject.CLASS_NUMBER == t)
373             return obj2.num() == num();
374     }
375     catch(javax.xml.transform.TransformerException JavaDoc te)
376     {
377         throw new org.apache.xml.utils.WrappedRuntimeException(te);
378     }
379
380     // Otherwise, both objects to be compared are converted to strings as
381
// if by applying the string function.
382
return xstr().equals(obj2.xstr());
383   }
384
385   /**
386    * Compares this string to the specified object.
387    * The result is <code>true</code> if and only if the argument is not
388    * <code>null</code> and is a <code>String</code> object that represents
389    * the same sequence of characters as this object.
390    *
391    * @param obj2 the object to compare this <code>String</code>
392    * against.
393    * @return <code>true</code> if the <code>String </code>are equal;
394    * <code>false</code> otherwise.
395    * @see java.lang.String#compareTo(java.lang.String)
396    * @see java.lang.String#equalsIgnoreCase(java.lang.String)
397    */

398   public boolean equals(XMLString obj2)
399   {
400
401     if (!obj2.hasString())
402       return obj2.equals(this);
403     else
404       return str().equals(obj2.toString());
405   }
406
407   /**
408    * Compares this string to the specified object.
409    * The result is <code>true</code> if and only if the argument is not
410    * <code>null</code> and is a <code>String</code> object that represents
411    * the same sequence of characters as this object.
412    *
413    * @param anObject the object to compare this <code>String</code>
414    * against.
415    *
416    * NEEDSDOC @param obj2
417    * @return <code>true</code> if the <code>String </code>are equal;
418    * <code>false</code> otherwise.
419    * @see java.lang.String#compareTo(java.lang.String)
420    * @see java.lang.String#equalsIgnoreCase(java.lang.String)
421    */

422   public boolean equals(Object JavaDoc obj2)
423   {
424
425     if (null == obj2)
426       return false;
427
428       // In order to handle the 'all' semantics of
429
// nodeset comparisons, we always call the
430
// nodeset function.
431
else if (obj2 instanceof XNodeSet)
432       return obj2.equals(this);
433     else if(obj2 instanceof XNumber)
434         return obj2.equals(this);
435     else
436       return str().equals(obj2.toString());
437   }
438
439   /**
440    * Compares this <code>String</code> to another <code>String</code>,
441    * ignoring case considerations. Two strings are considered equal
442    * ignoring case if they are of the same length, and corresponding
443    * characters in the two strings are equal ignoring case.
444    *
445    * @param anotherString the <code>String</code> to compare this
446    * <code>String</code> against.
447    * @return <code>true</code> if the argument is not <code>null</code>
448    * and the <code>String</code>s are equal,
449    * ignoring case; <code>false</code> otherwise.
450    * @see #equals(Object)
451    * @see java.lang.Character#toLowerCase(char)
452    * @see java.lang.Character#toUpperCase(char)
453    */

454   public boolean equalsIgnoreCase(String JavaDoc anotherString)
455   {
456     return str().equalsIgnoreCase(anotherString);
457   }
458
459   /**
460    * Compares two strings lexicographically.
461    *
462    * @param anotherString the <code>String</code> to be compared.
463    *
464    * NEEDSDOC @param xstr
465    * @return the value <code>0</code> if the argument string is equal to
466    * this string; a value less than <code>0</code> if this string
467    * is lexicographically less than the string argument; and a
468    * value greater than <code>0</code> if this string is
469    * lexicographically greater than the string argument.
470    * @exception java.lang.NullPointerException if <code>anotherString</code>
471    * is <code>null</code>.
472    */

473   public int compareTo(XMLString xstr)
474   {
475
476     int len1 = this.length();
477     int len2 = xstr.length();
478     int n = Math.min(len1, len2);
479     int i = 0;
480     int j = 0;
481
482     while (n-- != 0)
483     {
484       char c1 = this.charAt(i);
485       char c2 = xstr.charAt(j);
486
487       if (c1 != c2)
488       {
489         return c1 - c2;
490       }
491
492       i++;
493       j++;
494     }
495
496     return len1 - len2;
497   }
498
499   /**
500    * Compares two strings lexicographically, ignoring case considerations.
501    * This method returns an integer whose sign is that of
502    * <code>this.toUpperCase().toLowerCase().compareTo(
503    * str.toUpperCase().toLowerCase())</code>.
504    * <p>
505    * Note that this method does <em>not</em> take locale into account,
506    * and will result in an unsatisfactory ordering for certain locales.
507    * The java.text package provides <em>collators</em> to allow
508    * locale-sensitive ordering.
509    *
510    * @param str the <code>String</code> to be compared.
511    * @return a negative integer, zero, or a positive integer as the
512    * the specified String is greater than, equal to, or less
513    * than this String, ignoring case considerations.
514    * @see java.text.Collator#compare(String, String)
515    * @since 1.2
516    */

517   public int compareToIgnoreCase(XMLString str)
518   {
519     // %REVIEW% Like it says, @since 1.2. Doesn't exist in earlier
520
// versions of Java, hence we can't yet shell out to it. We can implement
521
// it as character-by-character compare, but doing so efficiently
522
// is likely to be (ahem) interesting.
523
//
524
// However, since nobody is actually _using_ this method yet:
525
// return str().compareToIgnoreCase(str.toString());
526

527     throw new org.apache.xml.utils.WrappedRuntimeException(
528       new java.lang.NoSuchMethodException JavaDoc(
529         "Java 1.2 method, not yet implemented"));
530   }
531
532   /**
533    * Tests if this string starts with the specified prefix beginning
534    * a specified index.
535    *
536    * @param prefix the prefix.
537    * @param toffset where to begin looking in the string.
538    * @return <code>true</code> if the character sequence represented by the
539    * argument is a prefix of the substring of this object starting
540    * at index <code>toffset</code>; <code>false</code> otherwise.
541    * The result is <code>false</code> if <code>toffset</code> is
542    * negative or greater than the length of this
543    * <code>String</code> object; otherwise the result is the same
544    * as the result of the expression
545    * <pre>
546    * this.subString(toffset).startsWith(prefix)
547    * </pre>
548    * @exception java.lang.NullPointerException if <code>prefix</code> is
549    * <code>null</code>.
550    */

551   public boolean startsWith(String JavaDoc prefix, int toffset)
552   {
553     return str().startsWith(prefix, toffset);
554   }
555
556   /**
557    * Tests if this string starts with the specified prefix.
558    *
559    * @param prefix the prefix.
560    * @return <code>true</code> if the character sequence represented by the
561    * argument is a prefix of the character sequence represented by
562    * this string; <code>false</code> otherwise.
563    * Note also that <code>true</code> will be returned if the
564    * argument is an empty string or is equal to this
565    * <code>String</code> object as determined by the
566    * {@link #equals(Object)} method.
567    * @exception java.lang.NullPointerException if <code>prefix</code> is
568    * <code>null</code>.
569    */

570   public boolean startsWith(String JavaDoc prefix)
571   {
572     return startsWith(prefix, 0);
573   }
574
575   /**
576    * Tests if this string starts with the specified prefix beginning
577    * a specified index.
578    *
579    * @param prefix the prefix.
580    * @param toffset where to begin looking in the string.
581    * @return <code>true</code> if the character sequence represented by the
582    * argument is a prefix of the substring of this object starting
583    * at index <code>toffset</code>; <code>false</code> otherwise.
584    * The result is <code>false</code> if <code>toffset</code> is
585    * negative or greater than the length of this
586    * <code>String</code> object; otherwise the result is the same
587    * as the result of the expression
588    * <pre>
589    * this.subString(toffset).startsWith(prefix)
590    * </pre>
591    * @exception java.lang.NullPointerException if <code>prefix</code> is
592    * <code>null</code>.
593    */

594   public boolean startsWith(XMLString prefix, int toffset)
595   {
596
597     int to = toffset;
598     int tlim = this.length();
599     int po = 0;
600     int pc = prefix.length();
601
602     // Note: toffset might be near -1>>>1.
603
if ((toffset < 0) || (toffset > tlim - pc))
604     {
605       return false;
606     }
607
608     while (--pc >= 0)
609     {
610       if (this.charAt(to) != prefix.charAt(po))
611       {
612         return false;
613       }
614
615       to++;
616       po++;
617     }
618
619     return true;
620   }
621
622   /**
623    * Tests if this string starts with the specified prefix.
624    *
625    * @param prefix the prefix.
626    * @return <code>true</code> if the character sequence represented by the
627    * argument is a prefix of the character sequence represented by
628    * this string; <code>false</code> otherwise.
629    * Note also that <code>true</code> will be returned if the
630    * argument is an empty string or is equal to this
631    * <code>String</code> object as determined by the
632    * {@link #equals(Object)} method.
633    * @exception java.lang.NullPointerException if <code>prefix</code> is
634    * <code>null</code>.
635    */

636   public boolean startsWith(XMLString prefix)
637   {
638     return startsWith(prefix, 0);
639   }
640
641   /**
642    * Tests if this string ends with the specified suffix.
643    *
644    * @param suffix the suffix.
645    * @return <code>true</code> if the character sequence represented by the
646    * argument is a suffix of the character sequence represented by
647    * this object; <code>false</code> otherwise. Note that the
648    * result will be <code>true</code> if the argument is the
649    * empty string or is equal to this <code>String</code> object
650    * as determined by the {@link #equals(Object)} method.
651    * @exception java.lang.NullPointerException if <code>suffix</code> is
652    * <code>null</code>.
653    */

654   public boolean endsWith(String JavaDoc suffix)
655   {
656     return str().endsWith(suffix);
657   }
658
659   /**
660    * Returns a hashcode for this string. The hashcode for a
661    * <code>String</code> object is computed as
662    * <blockquote><pre>
663    * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
664    * </pre></blockquote>
665    * using <code>int</code> arithmetic, where <code>s[i]</code> is the
666    * <i>i</i>th character of the string, <code>n</code> is the length of
667    * the string, and <code>^</code> indicates exponentiation.
668    * (The hash value of the empty string is zero.)
669    *
670    * @return a hash code value for this object.
671    */

672   public int hashCode()
673   {
674     return str().hashCode();
675   }
676
677   /**
678    * Returns the index within this string of the first occurrence of the
679    * specified character. If a character with value <code>ch</code> occurs
680    * in the character sequence represented by this <code>String</code>
681    * object, then the index of the first such occurrence is returned --
682    * that is, the smallest value <i>k</i> such that:
683    * <blockquote><pre>
684    * this.charAt(<i>k</i>) == ch
685    * </pre></blockquote>
686    * is <code>true</code>. If no such character occurs in this string,
687    * then <code>-1</code> is returned.
688    *
689    * @param ch a character.
690    * @return the index of the first occurrence of the character in the
691    * character sequence represented by this object, or
692    * <code>-1</code> if the character does not occur.
693    */

694   public int indexOf(int ch)
695   {
696     return str().indexOf(ch);
697   }
698
699   /**
700    * Returns the index within this string of the first occurrence of the
701    * specified character, starting the search at the specified index.
702    * <p>
703    * If a character with value <code>ch</code> occurs in the character
704    * sequence represented by this <code>String</code> object at an index
705    * no smaller than <code>fromIndex</code>, then the index of the first
706    * such occurrence is returned--that is, the smallest value <i>k</i>
707    * such that:
708    * <blockquote><pre>
709    * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
710    * </pre></blockquote>
711    * is true. If no such character occurs in this string at or after
712    * position <code>fromIndex</code>, then <code>-1</code> is returned.
713    * <p>
714    * There is no restriction on the value of <code>fromIndex</code>. If it
715    * is negative, it has the same effect as if it were zero: this entire
716    * string may be searched. If it is greater than the length of this
717    * string, it has the same effect as if it were equal to the length of
718    * this string: <code>-1</code> is returned.
719    *
720    * @param ch a character.
721    * @param fromIndex the index to start the search from.
722    * @return the index of the first occurrence of the character in the
723    * character sequence represented by this object that is greater
724    * than or equal to <code>fromIndex</code>, or <code>-1</code>
725    * if the character does not occur.
726    */

727   public int indexOf(int ch, int fromIndex)
728   {
729     return str().indexOf(ch, fromIndex);
730   }
731
732   /**
733    * Returns the index within this string of the last occurrence of the
734    * specified character. That is, the index returned is the largest
735    * value <i>k</i> such that:
736    * <blockquote><pre>
737    * this.charAt(<i>k</i>) == ch
738    * </pre></blockquote>
739    * is true.
740    * The String is searched backwards starting at the last character.
741    *
742    * @param ch a character.
743    * @return the index of the last occurrence of the character in the
744    * character sequence represented by this object, or
745    * <code>-1</code> if the character does not occur.
746    */

747   public int lastIndexOf(int ch)
748   {
749     return str().lastIndexOf(ch);
750   }
751
752   /**
753    * Returns the index within this string of the last occurrence of the
754    * specified character, searching backward starting at the specified
755    * index. That is, the index returned is the largest value <i>k</i>
756    * such that:
757    * <blockquote><pre>
758    * this.charAt(k) == ch) && (k <= fromIndex)
759    * </pre></blockquote>
760    * is true.
761    *
762    * @param ch a character.
763    * @param fromIndex the index to start the search from. There is no
764    * restriction on the value of <code>fromIndex</code>. If it is
765    * greater than or equal to the length of this string, it has
766    * the same effect as if it were equal to one less than the
767    * length of this string: this entire string may be searched.
768    * If it is negative, it has the same effect as if it were -1:
769    * -1 is returned.
770    * @return the index of the last occurrence of the character in the
771    * character sequence represented by this object that is less
772    * than or equal to <code>fromIndex</code>, or <code>-1</code>
773    * if the character does not occur before that point.
774    */

775   public int lastIndexOf(int ch, int fromIndex)
776   {
777     return str().lastIndexOf(ch, fromIndex);
778   }
779
780   /**
781    * Returns the index within this string of the first occurrence of the
782    * specified substring. The integer returned is the smallest value
783    * <i>k</i> such that:
784    * <blockquote><pre>
785    * this.startsWith(str, <i>k</i>)
786    * </pre></blockquote>
787    * is <code>true</code>.
788    *
789    * @param str any string.
790    * @return if the string argument occurs as a substring within this
791    * object, then the index of the first character of the first
792    * such substring is returned; if it does not occur as a
793    * substring, <code>-1</code> is returned.
794    * @exception java.lang.NullPointerException if <code>str</code> is
795    * <code>null</code>.
796    */

797   public int indexOf(String JavaDoc str)
798   {
799     return str().indexOf(str);
800   }
801
802   /**
803    * Returns the index within this string of the first occurrence of the
804    * specified substring. The integer returned is the smallest value
805    * <i>k</i> such that:
806    * <blockquote><pre>
807    * this.startsWith(str, <i>k</i>)
808    * </pre></blockquote>
809    * is <code>true</code>.
810    *
811    * @param str any string.
812    * @return if the string argument occurs as a substring within this
813    * object, then the index of the first character of the first
814    * such substring is returned; if it does not occur as a
815    * substring, <code>-1</code> is returned.
816    * @exception java.lang.NullPointerException if <code>str</code> is
817    * <code>null</code>.
818    */

819   public int indexOf(XMLString str)
820   {
821     return str().indexOf(str.toString());
822   }
823
824   /**
825    * Returns the index within this string of the first occurrence of the
826    * specified substring, starting at the specified index. The integer
827    * returned is the smallest value <i>k</i> such that:
828    * <blockquote><pre>
829    * this.startsWith(str, <i>k</i>) && (<i>k</i> >= fromIndex)
830    * </pre></blockquote>
831    * is <code>true</code>.
832    * <p>
833    * There is no restriction on the value of <code>fromIndex</code>. If
834    * it is negative, it has the same effect as if it were zero: this entire
835    * string may be searched. If it is greater than the length of this
836    * string, it has the same effect as if it were equal to the length of
837    * this string: <code>-1</code> is returned.
838    *
839    * @param str the substring to search for.
840    * @param fromIndex the index to start the search from.
841    * @return If the string argument occurs as a substring within this
842    * object at a starting index no smaller than
843    * <code>fromIndex</code>, then the index of the first character
844    * of the first such substring is returned. If it does not occur
845    * as a substring starting at <code>fromIndex</code> or beyond,
846    * <code>-1</code> is returned.
847    * @exception java.lang.NullPointerException if <code>str</code> is
848    * <code>null</code>
849    */

850   public int indexOf(String JavaDoc str, int fromIndex)
851   {
852     return str().indexOf(str, fromIndex);
853   }
854
855   /**
856    * Returns the index within this string of the rightmost occurrence
857    * of the specified substring. The rightmost empty string "" is
858    * considered to occur at the index value <code>this.length()</code>.
859    * The returned index is the largest value <i>k</i> such that
860    * <blockquote><pre>
861    * this.startsWith(str, k)
862    * </pre></blockquote>
863    * is true.
864    *
865    * @param str the substring to search for.
866    * @return if the string argument occurs one or more times as a substring
867    * within this object, then the index of the first character of
868    * the last such substring is returned. If it does not occur as
869    * a substring, <code>-1</code> is returned.
870    * @exception java.lang.NullPointerException if <code>str</code> is
871    * <code>null</code>.
872    */

873   public int lastIndexOf(String JavaDoc str)
874   {
875     return str().lastIndexOf(str);
876   }
877
878   /**
879    * Returns the index within this string of the last occurrence of
880    * the specified substring.
881    *
882    * @param str the substring to search for.
883    * @param fromIndex the index to start the search from. There is no
884    * restriction on the value of fromIndex. If it is greater than
885    * the length of this string, it has the same effect as if it
886    * were equal to the length of this string: this entire string
887    * may be searched. If it is negative, it has the same effect
888    * as if it were -1: -1 is returned.
889    * @return If the string argument occurs one or more times as a substring
890    * within this object at a starting index no greater than
891    * <code>fromIndex</code>, then the index of the first character of
892    * the last such substring is returned. If it does not occur as a
893    * substring starting at <code>fromIndex</code> or earlier,
894    * <code>-1</code> is returned.
895    * @exception java.lang.NullPointerException if <code>str</code> is
896    * <code>null</code>.
897    */

898   public int lastIndexOf(String JavaDoc str, int fromIndex)
899   {
900     return str().lastIndexOf(str, fromIndex);
901   }
902
903   /**
904    * Returns a new string that is a substring of this string. The
905    * substring begins with the character at the specified index and
906    * extends to the end of this string. <p>
907    * Examples:
908    * <blockquote><pre>
909    * "unhappy".substring(2) returns "happy"
910    * "Harbison".substring(3) returns "bison"
911    * "emptiness".substring(9) returns "" (an empty string)
912    * </pre></blockquote>
913    *
914    * @param beginIndex the beginning index, inclusive.
915    * @return the specified substring.
916    * @exception IndexOutOfBoundsException if
917    * <code>beginIndex</code> is negative or larger than the
918    * length of this <code>String</code> object.
919    */

920   public XMLString substring(int beginIndex)
921   {
922     return new XString(str().substring(beginIndex));
923   }
924
925   /**
926    * Returns a new string that is a substring of this string. The
927    * substring begins at the specified <code>beginIndex</code> and
928    * extends to the character at index <code>endIndex - 1</code>.
929    * Thus the length of the substring is <code>endIndex-beginIndex</code>.
930    *
931    * @param beginIndex the beginning index, inclusive.
932    * @param endIndex the ending index, exclusive.
933    * @return the specified substring.
934    * @exception IndexOutOfBoundsException if the
935    * <code>beginIndex</code> is negative, or
936    * <code>endIndex</code> is larger than the length of
937    * this <code>String</code> object, or
938    * <code>beginIndex</code> is larger than
939    * <code>endIndex</code>.
940    */

941   public XMLString substring(int beginIndex, int endIndex)
942   {
943     return new XString(str().substring(beginIndex, endIndex));
944   }
945
946   /**
947    * Concatenates the specified string to the end of this string.
948    *
949    * @param str the <code>String</code> that is concatenated to the end
950    * of this <code>String</code>.
951    * @return a string that represents the concatenation of this object's
952    * characters followed by the string argument's characters.
953    * @exception java.lang.NullPointerException if <code>str</code> is
954    * <code>null</code>.
955    */

956   public XMLString concat(String JavaDoc str)
957   {
958
959     // %REVIEW% Make an FSB here?
960
return new XString(str().concat(str));
961   }
962
963   /**
964    * Converts all of the characters in this <code>String</code> to lower
965    * case using the rules of the given <code>Locale</code>.
966    *
967    * @param locale use the case transformation rules for this locale
968    * @return the String, converted to lowercase.
969    * @see java.lang.Character#toLowerCase(char)
970    * @see java.lang.String#toUpperCase(Locale)
971    */

972   public XMLString toLowerCase(Locale JavaDoc locale)
973   {
974     return new XString(str().toLowerCase(locale));
975   }
976
977   /**
978    * Converts all of the characters in this <code>String</code> to lower
979    * case using the rules of the default locale, which is returned
980    * by <code>Locale.getDefault</code>.
981    * <p>
982    *
983    * @return the string, converted to lowercase.
984    * @see java.lang.Character#toLowerCase(char)
985    * @see java.lang.String#toLowerCase(Locale)
986    */

987   public XMLString toLowerCase()
988   {
989     return new XString(str().toLowerCase());
990   }
991
992   /**
993    * Converts all of the characters in this <code>String</code> to upper
994    * case using the rules of the given locale.
995    * @param locale use the case transformation rules for this locale
996    * @return the String, converted to uppercase.
997    * @see java.lang.Character#toUpperCase(char)
998    * @see java.lang.String#toLowerCase(Locale)
999    */

1000  public XMLString toUpperCase(Locale JavaDoc locale)
1001  {
1002    return new XString(str().toUpperCase(locale));
1003  }
1004
1005  /**
1006   * Converts all of the characters in this <code>String</code> to upper
1007   * case using the rules of the default locale, which is returned
1008   * by <code>Locale.getDefault</code>.
1009   *
1010   * <p>
1011   * If no character in this string has a different uppercase version,
1012   * based on calling the <code>toUpperCase</code> method defined by
1013   * <code>Character</code>, then the original string is returned.
1014   * <p>
1015   * Otherwise, this method creates a new <code>String</code> object
1016   * representing a character sequence identical in length to the
1017   * character sequence represented by this <code>String</code> object and
1018   * with every character equal to the result of applying the method
1019   * <code>Character.toUpperCase</code> to the corresponding character of
1020   * this <code>String</code> object. <p>
1021   * Examples:
1022   * <blockquote><pre>
1023   * "Fahrvergnügen".toUpperCase() returns "FAHRVERGNÜGEN"
1024   * "Visit Ljubinje!".toUpperCase() returns "VISIT LJUBINJE!"
1025   * </pre></blockquote>
1026   *
1027   * @return the string, converted to uppercase.
1028   * @see java.lang.Character#toUpperCase(char)
1029   * @see java.lang.String#toUpperCase(Locale)
1030   */

1031  public XMLString toUpperCase()
1032  {
1033    return new XString(str().toUpperCase());
1034  }
1035
1036  /**
1037   * Removes white space from both ends of this string.
1038   *
1039   * @return this string, with white space removed from the front and end.
1040   */

1041  public XMLString trim()
1042  {
1043    return new XString(str().trim());
1044  }
1045
1046  /**
1047   * Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition
1048   * of whitespace. Refer to <A HREF="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S">
1049   * the definition of <CODE>S</CODE></A> for details.
1050   * @param ch Character to check as XML whitespace.
1051   * @return =true if <var>ch</var> is XML whitespace; otherwise =false.
1052   */

1053  private static boolean isSpace(char ch)
1054  {
1055    return XMLCharacterRecognizer.isWhiteSpace(ch); // Take the easy way out for now.
1056
}
1057
1058  /**
1059   * Conditionally trim all leading and trailing whitespace in the specified String.
1060   * All strings of white space are
1061   * replaced by a single space character (#x20), except spaces after punctuation which
1062   * receive double spaces if doublePunctuationSpaces is true.
1063   * This function may be useful to a formatter, but to get first class
1064   * results, the formatter should probably do it's own white space handling
1065   * based on the semantics of the formatting object.
1066   *
1067   * @param trimHead Trim leading whitespace?
1068   * @param trimTail Trim trailing whitespace?
1069   * @param doublePunctuationSpaces Use double spaces for punctuation?
1070   * @return The trimmed string.
1071   */

1072  public XMLString fixWhiteSpace(boolean trimHead, boolean trimTail,
1073                                 boolean doublePunctuationSpaces)
1074  {
1075
1076    // %OPT% !!!!!!!
1077
int len = this.length();
1078    char[] buf = new char[len];
1079
1080    this.getChars(0, len, buf, 0);
1081
1082    boolean edit = false;
1083    int s;
1084
1085    for (s = 0; s < len; s++)
1086    {
1087      if (isSpace(buf[s]))
1088      {
1089        break;
1090      }
1091    }
1092
1093    /* replace S to ' '. and ' '+ -> single ' '. */
1094    int d = s;
1095    boolean pres = false;
1096
1097    for (; s < len; s++)
1098    {
1099      char c = buf[s];
1100
1101      if (isSpace(c))
1102      {
1103        if (!pres)
1104        {
1105          if (' ' != c)
1106          {
1107            edit = true;
1108          }
1109
1110          buf[d++] = ' ';
1111
1112          if (doublePunctuationSpaces && (s != 0))
1113          {
1114            char prevChar = buf[s - 1];
1115
1116            if (!((prevChar == '.') || (prevChar == '!')
1117                  || (prevChar == '?')))
1118            {
1119              pres = true;
1120            }
1121          }
1122          else
1123          {
1124            pres = true;
1125          }
1126        }
1127        else
1128        {
1129          edit = true;
1130          pres = true;
1131        }
1132      }
1133      else
1134      {
1135        buf[d++] = c;
1136        pres = false;
1137      }
1138    }
1139
1140    if (trimTail && 1 <= d && ' ' == buf[d - 1])
1141    {
1142      edit = true;
1143
1144      d--;
1145    }
1146
1147    int start = 0;
1148
1149    if (trimHead && 0 < d && ' ' == buf[0])
1150    {
1151      edit = true;
1152
1153      start++;
1154    }
1155
1156    XMLStringFactory xsf = XMLStringFactoryImpl.getFactory();
1157
1158    return edit ? xsf.newstr(new String JavaDoc(buf, start, d - start)) : this;
1159  }
1160  
1161  /**
1162   * @see XPathVisitable#callVisitors(ExpressionOwner, XPathVisitor)
1163   */

1164  public void callVisitors(ExpressionOwner owner, XPathVisitor visitor)
1165  {
1166    visitor.visitStringLiteral(owner, this);
1167  }
1168
1169}
1170
Popular Tags