1. /*
  2. * The Apache Software License, Version 1.1
  3. *
  4. *
  5. * Copyright (c) 1999 The Apache Software Foundation. All rights
  6. * reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. The end-user documentation included with the redistribution,
  21. * if any, must include the following acknowledgment:
  22. * "This product includes software developed by the
  23. * Apache Software Foundation (http://www.apache.org/)."
  24. * Alternately, this acknowledgment may appear in the software itself,
  25. * if and wherever such third-party acknowledgments normally appear.
  26. *
  27. * 4. The names "Xalan" and "Apache Software Foundation" must
  28. * not be used to endorse or promote products derived from this
  29. * software without prior written permission. For written
  30. * permission, please contact apache@apache.org.
  31. *
  32. * 5. Products derived from this software may not be called "Apache",
  33. * nor may "Apache" appear in their name, without prior written
  34. * permission of the Apache Software Foundation.
  35. *
  36. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  37. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  38. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  40. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  42. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  43. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  44. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  45. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  46. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. * ====================================================================
  49. *
  50. * This software consists of voluntary contributions made by many
  51. * individuals on behalf of the Apache Software Foundation and was
  52. * originally based on software copyright (c) 1999, Lotus
  53. * Development Corporation., http://www.lotus.com. For more
  54. * information on the Apache Software Foundation, please see
  55. * <http://www.apache.org/>.
  56. */
  57. package org.apache.xalan.transformer;
  58. import org.w3c.dom.Element;
  59. import org.w3c.dom.Node;
  60. import java.util.Locale;
  61. import java.util.NoSuchElementException;
  62. /**
  63. * <meta name="usage" content="internal"/>
  64. * Converts enumerated numbers into strings, using the XSL conversion attributes.
  65. * Having this in a class helps avoid being forced to extract the attributes repeatedly.
  66. */
  67. class NumeratorFormatter
  68. {
  69. /** The owning xsl:number element. */
  70. protected Element m_xslNumberElement;
  71. /** An instance of a Tokenizer */
  72. NumberFormatStringTokenizer m_formatTokenizer;
  73. /** Locale we need to format in */
  74. Locale m_locale;
  75. /** An instance of a NumberFormat */
  76. java.text.NumberFormat m_formatter;
  77. /** An instance of a transformer */
  78. TransformerImpl m_processor;
  79. /**
  80. * Table to help in converting decimals to roman numerals.
  81. * @see org.apache.xalan.transformer.DecimalToRoman
  82. */
  83. private final static DecimalToRoman m_romanConvertTable[] = {
  84. new DecimalToRoman(1000, "M", 900, "CM"),
  85. new DecimalToRoman(500, "D", 400, "CD"),
  86. new DecimalToRoman(100L, "C", 90L, "XC"),
  87. new DecimalToRoman(50L, "L", 40L, "XL"),
  88. new DecimalToRoman(10L, "X", 9L, "IX"),
  89. new DecimalToRoman(5L, "V", 4L, "IV"),
  90. new DecimalToRoman(1L, "I", 1L, "I") };
  91. /**
  92. * Chars for converting integers into alpha counts.
  93. * @see TransformerImpl#int2alphaCount
  94. */
  95. private final static char[] m_alphaCountTable = { 'Z', // z for zero
  96. 'A', 'B', 'C', 'D', 'E',
  97. 'F', 'G', 'H', 'I', 'J',
  98. 'K', 'L', 'M', 'N', 'O',
  99. 'P', 'Q', 'R', 'S', 'T',
  100. 'U', 'V', 'W', 'X', 'Y' };
  101. /**
  102. * Construct a NumeratorFormatter using an element
  103. * that contains XSL number conversion attributes -
  104. * format, letter-value, xml:lang, digit-group-sep,
  105. * n-digits-per-group, and sequence-src.
  106. *
  107. * @param xslNumberElement The given xsl:number element
  108. * @param processor a non-null transformer instance
  109. */
  110. NumeratorFormatter(Element xslNumberElement, TransformerImpl processor)
  111. {
  112. m_xslNumberElement = xslNumberElement;
  113. m_processor = processor;
  114. } // end NumeratorFormatter(Element) constructor
  115. /**
  116. * Convert a long integer into alphabetic counting, in other words
  117. * count using the sequence A B C ... Z AA AB AC.... etc.
  118. *
  119. * @param val Value to convert -- must be greater than zero.
  120. * @param table a table containing one character for each digit in the radix
  121. * @return String representing alpha count of number.
  122. * @see org.apache.xalan.transformer.DecimalToRoman
  123. *
  124. * Note that the radix of the conversion is inferred from the size
  125. * of the table.
  126. */
  127. protected String int2alphaCount(int val, char[] table)
  128. {
  129. int radix = table.length;
  130. // Create a buffer to hold the result
  131. // TODO: size of the table can be detereined by computing
  132. // logs of the radix. For now, we fake it.
  133. char buf[] = new char[100];
  134. // next character to set in the buffer
  135. int charPos = buf.length - 1; // work backward through buf[]
  136. // index in table of the last character that we stored
  137. int lookupIndex = 1; // start off with anything other than zero to make correction work
  138. // Correction number
  139. //
  140. // Correction can take on exactly two values:
  141. //
  142. // 0 if the next character is to be emitted is usual
  143. //
  144. // radix - 1
  145. // if the next char to be emitted should be one less than
  146. // you would expect
  147. //
  148. // For example, consider radix 10, where 1="A" and 10="J"
  149. //
  150. // In this scheme, we count: A, B, C ... H, I, J (not A0 and certainly
  151. // not AJ), A1
  152. //
  153. // So, how do we keep from emitting AJ for 10? After correctly emitting the
  154. // J, lookupIndex is zero. We now compute a correction number of 9 (radix-1).
  155. // In the following line, we'll compute (val+correction) % radix, which is,
  156. // (val+9)/10. By this time, val is 1, so we compute (1+9) % 10, which
  157. // is 10 % 10 or zero. So, we'll prepare to emit "JJ", but then we'll
  158. // later suppress the leading J as representing zero (in the mod system,
  159. // it can represent either 10 or zero). In summary, the correction value of
  160. // "radix-1" acts like "-1" when run through the mod operator, but with the
  161. // desireable characteristic that it never produces a negative number.
  162. int correction = 0;
  163. // TODO: throw error on out of range input
  164. do
  165. {
  166. // most of the correction calculation is explained above, the reason for the
  167. // term after the "|| " is that it correctly propagates carries across
  168. // multiple columns.
  169. correction =
  170. ((lookupIndex == 0) || (correction != 0 && lookupIndex == radix - 1))
  171. ? (radix - 1) : 0;
  172. // index in "table" of the next char to emit
  173. lookupIndex = (val + correction) % radix;
  174. // shift input by one "column"
  175. val = (val / radix);
  176. // if the next value we'd put out would be a leading zero, we're done.
  177. if (lookupIndex == 0 && val == 0)
  178. break;
  179. // put out the next character of output
  180. buf[charPos--] = table[lookupIndex];
  181. }
  182. while (val > 0);
  183. return new String(buf, charPos + 1, (buf.length - charPos - 1));
  184. }
  185. /**
  186. * Convert a long integer into roman numerals.
  187. * @param val Value to convert.
  188. * @param prefixesAreOK true_ to enable prefix notation (e.g. 4 = "IV"),
  189. * false_ to disable prefix notation (e.g. 4 = "IIII").
  190. * @return Roman numeral string.
  191. * @see DecimalToRoman
  192. * @see m_romanConvertTable
  193. */
  194. String long2roman(long val, boolean prefixesAreOK)
  195. {
  196. if (val <= 0)
  197. {
  198. return "#E(" + val + ")";
  199. }
  200. String roman = "";
  201. int place = 0;
  202. if (val <= 3999L)
  203. {
  204. do
  205. {
  206. while (val >= m_romanConvertTable[place].m_postValue)
  207. {
  208. roman += m_romanConvertTable[place].m_postLetter;
  209. val -= m_romanConvertTable[place].m_postValue;
  210. }
  211. if (prefixesAreOK)
  212. {
  213. if (val >= m_romanConvertTable[place].m_preValue)
  214. {
  215. roman += m_romanConvertTable[place].m_preLetter;
  216. val -= m_romanConvertTable[place].m_preValue;
  217. }
  218. }
  219. place++;
  220. }
  221. while (val > 0);
  222. }
  223. else
  224. {
  225. roman = "#error";
  226. }
  227. return roman;
  228. } // end long2roman
  229. /**
  230. * This class returns tokens using non-alphanumberic
  231. * characters as delimiters.
  232. */
  233. class NumberFormatStringTokenizer
  234. {
  235. /** Field holding the current position in the string */
  236. private int currentPosition;
  237. /** The total length of the string */
  238. private int maxPosition;
  239. /** The string to tokenize */
  240. private String str;
  241. /**
  242. * Construct a NumberFormatStringTokenizer.
  243. *
  244. * @param str The string to tokenize
  245. */
  246. NumberFormatStringTokenizer(String str)
  247. {
  248. this.str = str;
  249. maxPosition = str.length();
  250. }
  251. /**
  252. * Reset tokenizer so that nextToken() starts from the beginning.
  253. *
  254. */
  255. void reset()
  256. {
  257. currentPosition = 0;
  258. }
  259. /**
  260. * Returns the next token from this string tokenizer.
  261. *
  262. * @return the next token from this string tokenizer.
  263. * @throws NoSuchElementException if there are no more tokens in this
  264. * tokenizer's string.
  265. */
  266. String nextToken()
  267. {
  268. if (currentPosition >= maxPosition)
  269. {
  270. throw new NoSuchElementException();
  271. }
  272. int start = currentPosition;
  273. while ((currentPosition < maxPosition)
  274. && Character.isLetterOrDigit(str.charAt(currentPosition)))
  275. {
  276. currentPosition++;
  277. }
  278. if ((start == currentPosition)
  279. && (!Character.isLetterOrDigit(str.charAt(currentPosition))))
  280. {
  281. currentPosition++;
  282. }
  283. return str.substring(start, currentPosition);
  284. }
  285. /**
  286. * Tells if <code>nextToken</code> will throw an exception * if it is called.
  287. *
  288. * @return true if <code>nextToken</code> can be called * without throwing an exception.
  289. */
  290. boolean hasMoreTokens()
  291. {
  292. return (currentPosition >= maxPosition) ? false : true;
  293. }
  294. /**
  295. * Calculates the number of times that this tokenizer's
  296. * <code>nextToken</code> method can be called before it generates an
  297. * exception.
  298. *
  299. * @return the number of tokens remaining in the string using the current
  300. * delimiter set.
  301. * @see java.util.StringTokenizer#nextToken()
  302. */
  303. int countTokens()
  304. {
  305. int count = 0;
  306. int currpos = currentPosition;
  307. while (currpos < maxPosition)
  308. {
  309. int start = currpos;
  310. while ((currpos < maxPosition)
  311. && Character.isLetterOrDigit(str.charAt(currpos)))
  312. {
  313. currpos++;
  314. }
  315. if ((start == currpos)
  316. && (Character.isLetterOrDigit(str.charAt(currpos)) == false))
  317. {
  318. currpos++;
  319. }
  320. count++;
  321. }
  322. return count;
  323. }
  324. } // end NumberFormatStringTokenizer
  325. }