1. /*
  2. * @(#)MessageFormat.java 1.56 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. /*
  8. * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
  9. * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
  10. *
  11. * The original version of this source code and documentation is copyrighted
  12. * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
  13. * materials are provided under terms of a License Agreement between Taligent
  14. * and Sun. This technology is protected by multiple US and International
  15. * patents. This notice and attribution to Taligent may not be removed.
  16. * Taligent is a registered trademark of Taligent, Inc.
  17. *
  18. */
  19. package java.text;
  20. import java.io.InvalidObjectException;
  21. import java.io.IOException;
  22. import java.io.ObjectInputStream;
  23. import java.text.DecimalFormat;
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.List;
  27. import java.util.Locale;
  28. import sun.text.Utility;
  29. /**
  30. * <code>MessageFormat</code> provides a means to produce concatenated
  31. * messages in language-neutral way. Use this to construct messages
  32. * displayed for end users.
  33. *
  34. * <p>
  35. * <code>MessageFormat</code> takes a set of objects, formats them, then
  36. * inserts the formatted strings into the pattern at the appropriate places.
  37. *
  38. * <p>
  39. * <strong>Note:</strong>
  40. * <code>MessageFormat</code> differs from the other <code>Format</code>
  41. * classes in that you create a <code>MessageFormat</code> object with one
  42. * of its constructors (not with a <code>getInstance</code> style factory
  43. * method). The factory methods aren't necessary because <code>MessageFormat</code>
  44. * itself doesn't implement locale specific behavior. Any locale specific
  45. * behavior is defined by the pattern that you provide as well as the
  46. * subformats used for inserted arguments.
  47. *
  48. * <h4><a name="patterns">Patterns and Their Interpretation</a></h4>
  49. *
  50. * <code>MessageFormat</code> uses patterns of the following form:
  51. * <blockquote><pre>
  52. * <i>MessageFormatPattern:</i>
  53. * <i>String</i>
  54. * <i>MessageFormatPattern</i> <i>FormatElement</i> <i>String</i>
  55. *
  56. * <i>FormatElement:</i>
  57. * { <i>ArgumentIndex</i> }
  58. * { <i>ArgumentIndex</i> , <i>FormatType</i> }
  59. * { <i>ArgumentIndex</i> , <i>FormatType</i> , <i>FormatStyle</i> }
  60. *
  61. * <i>FormatType: one of </i>
  62. * number date time choice
  63. *
  64. * <i>FormatStyle:</i>
  65. * short
  66. * medium
  67. * long
  68. * full
  69. * integer
  70. * currency
  71. * percent
  72. * <i>SubformatPattern</i>
  73. *
  74. * <i>String:</i>
  75. * <i>StringPart<sub>opt</sub></i>
  76. * <i>String</i> <i>StringPart</i>
  77. *
  78. * <i>StringPart:</i>
  79. * ''
  80. * ' <i>QuotedString</i> '
  81. * <i>UnquotedString</i>
  82. *
  83. * <i>SubformatPattern:</i>
  84. * <i>SubformatPatternPart<sub>opt</sub></i>
  85. * <i>SubformatPattern</i> <i>SubformatPatternPart</i>
  86. *
  87. * <i>SubFormatPatternPart:</i>
  88. * ' <i>QuotedPattern</i> '
  89. * <i>UnquotedPattern</i>
  90. * </pre></blockquote>
  91. *
  92. * <p>
  93. * Within a <i>String</i>, <code>"''"</code> represents a single
  94. * quote. A <i>QuotedString</i> can contain arbitrary characters
  95. * except single quotes; the surrounding single quotes are removed.
  96. * An <i>UnquotedString</i> can contain arbitrary characters
  97. * except single quotes and left curly brackets. Thus, a string that
  98. * should result in the formatted message "'{0}'" can be written as
  99. * <code>"'''{'0}''"</code> or <code>"'''{0}'''"</code>.
  100. * <p>
  101. * Within a <i>SubformatPattern</i>, different rules apply.
  102. * A <i>QuotedPattern</i> can contain arbitrary characters
  103. * except single quotes; but the surrounding single quotes are
  104. * <strong>not</strong> removed, so they may be interpreted by the
  105. * subformat. For example, <code>"{1,number,$'#',##}"</code> will
  106. * produce a number format with the pound-sign quoted, with a result
  107. * such as: "$#31,45".
  108. * An <i>UnquotedPattern</i> can contain arbitrary characters
  109. * except single quotes, but curly braces within it must be balanced.
  110. * For example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code>
  111. * are valid subformat patterns, but <code>"ab {0'}' de"</code> and
  112. * <code>"ab } de"</code> are not.
  113. * <p>
  114. * <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
  115. * format patterns unfortunately have shown to be somewhat confusing.
  116. * In particular, it isn't always obvious to localizers whether single
  117. * quotes need to be doubled or not. Make sure to inform localizers about
  118. * the rules, and tell them (for example, by using comments in resource
  119. * bundle source files) which strings will be processed by MessageFormat.
  120. * Note that localizers may need to use single quotes in translated
  121. * strings where the original version doesn't have them.
  122. * </dl>
  123. * <p>
  124. * The <i>ArgumentIndex</i> value is a non-negative integer written
  125. * using the digits '0' through '9', and represents an index into the
  126. * <code>arguments</code> array passed to the <code>format</code> methods
  127. * or the result array returned by the <code>parse</code> methods.
  128. * <p>
  129. * The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
  130. * a <code>Format</code> instance for the format element. The following
  131. * table shows how the values map to Format instances. Combinations not
  132. * shown in the table are illegal. A <i>SubformatPattern</i> must
  133. * be a valid pattern string for the Format subclass used.
  134. * <p>
  135. * <table border=1 summary="Shows how FormatType and FormatStyle values map to Format instances">
  136. * <tr>
  137. * <th id="ft">Format Type
  138. * <th id="fs">Format Style
  139. * <th id="sc">Subformat Created
  140. * <tr>
  141. * <td headers="ft"><i>(none)</i>
  142. * <td headers="fs"><i>(none)</i>
  143. * <td headers="sc"><code>null</code>
  144. * <tr>
  145. * <td headers="ft" rowspan=5><code>number</code>
  146. * <td headers="fs"><i>(none)</i>
  147. * <td headers="sc"><code>NumberFormat.getInstance(getLocale())</code>
  148. * <tr>
  149. * <td headers="fs"><code>integer</code>
  150. * <td headers="sc"><code>NumberFormat.getIntegerInstance(getLocale())</code>
  151. * <tr>
  152. * <td headers="fs"><code>currency</code>
  153. * <td headers="sc"><code>NumberFormat.getCurrencyInstance(getLocale())</code>
  154. * <tr>
  155. * <td headers="fs"><code>percent</code>
  156. * <td headers="sc"><code>NumberFormat.getPercentInstance(getLocale())</code>
  157. * <tr>
  158. * <td headers="fs"><i>SubformatPattern</i>
  159. * <td headers="sc"><code>new DecimalFormat(subformatPattern, new DecimalFormatSymbols(getLocale()))</code>
  160. * <tr>
  161. * <td headers="ft" rowspan=6><code>date</code>
  162. * <td headers="fs"><i>(none)</i>
  163. * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code>
  164. * <tr>
  165. * <td headers="fs"><code>short</code>
  166. * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.SHORT, getLocale())</code>
  167. * <tr>
  168. * <td headers="fs"><code>medium</code>
  169. * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.DEFAULT, getLocale())</code>
  170. * <tr>
  171. * <td headers="fs"><code>long</code>
  172. * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.LONG, getLocale())</code>
  173. * <tr>
  174. * <td headers="fs"><code>full</code>
  175. * <td headers="sc"><code>DateFormat.getDateInstance(DateFormat.FULL, getLocale())</code>
  176. * <tr>
  177. * <td headers="fs"><i>SubformatPattern</i>
  178. * <td headers="sc"><code>new SimpleDateFormat(subformatPattern, getLocale())
  179. * <tr>
  180. * <td headers="ft" rowspan=6><code>time</code>
  181. * <td headers="fs"><i>(none)</i>
  182. * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code>
  183. * <tr>
  184. * <td headers="fs"><code>short</code>
  185. * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.SHORT, getLocale())</code>
  186. * <tr>
  187. * <td headers="fs"><code>medium</code>
  188. * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale())</code>
  189. * <tr>
  190. * <td headers="fs"><code>long</code>
  191. * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.LONG, getLocale())</code>
  192. * <tr>
  193. * <td headers="fs"><code>full</code>
  194. * <td headers="sc"><code>DateFormat.getTimeInstance(DateFormat.FULL, getLocale())</code>
  195. * <tr>
  196. * <td headers="fs"><i>SubformatPattern</i>
  197. * <td headers="sc"><code>new SimpleDateFormat(subformatPattern, getLocale())
  198. * <tr>
  199. * <td headers="ft"><code>choice</code>
  200. * <td headers="fs"><i>SubformatPattern</i>
  201. * <td headers="sc"><code>new ChoiceFormat(subformatPattern)</code>
  202. * </table>
  203. * <p>
  204. *
  205. * <h4>Usage Information</h4>
  206. *
  207. * <p>
  208. * Here are some examples of usage.
  209. * In real internationalized programs, the message format pattern and other
  210. * static strings will, of course, be obtained from resource bundles.
  211. * Other parameters will be dynamically determined at runtime.
  212. * <p>
  213. * The first example uses the static method <code>MessageFormat.format</code>,
  214. * which internally creates a <code>MessageFormat</code> for one-time use:
  215. * <blockquote><pre>
  216. * int planet = 7;
  217. * String event = "a disturbance in the Force";
  218. *
  219. * String result = MessageFormat.format(
  220. * "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
  221. * planet, new Date(), event);
  222. * </pre></blockquote>
  223. * The output is:
  224. * <blockquote><pre>
  225. * At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
  226. * </pre></blockquote>
  227. *
  228. * <p>
  229. * The following example creates a <code>MessageFormat</code> instance that
  230. * can be used repeatedly:
  231. * <blockquote><pre>
  232. * int fileCount = 1273;
  233. * String diskName = "MyDisk";
  234. * Object[] testArgs = {new Long(fileCount), diskName};
  235. *
  236. * MessageFormat form = new MessageFormat(
  237. * "The disk \"{1}\" contains {0} file(s).");
  238. *
  239. * System.out.println(form.format(testArgs));
  240. * </pre></blockquote>
  241. * The output with different values for <code>fileCount</code>:
  242. * <blockquote><pre>
  243. * The disk "MyDisk" contains 0 file(s).
  244. * The disk "MyDisk" contains 1 file(s).
  245. * The disk "MyDisk" contains 1,273 file(s).
  246. * </pre></blockquote>
  247. *
  248. * <p>
  249. * For more sophisticated patterns, you can use a <code>ChoiceFormat</code>
  250. * to produce correct forms for singular and plural:
  251. * <blockquote><pre>
  252. * MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
  253. * double[] filelimits = {0,1,2};
  254. * String[] filepart = {"no files","one file","{0,number} files"};
  255. * ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
  256. * form.setFormatByArgumentIndex(0, fileform);
  257. *
  258. * int fileCount = 1273;
  259. * String diskName = "MyDisk";
  260. * Object[] testArgs = {new Long(fileCount), diskName};
  261. *
  262. * System.out.println(form.format(testArgs));
  263. * </pre></blockquote>
  264. * The output with different values for <code>fileCount</code>:
  265. * <blockquote><pre>
  266. * The disk "MyDisk" contains no files.
  267. * The disk "MyDisk" contains one file.
  268. * The disk "MyDisk" contains 1,273 files.
  269. * </pre></blockquote>
  270. *
  271. * <p>
  272. * You can create the <code>ChoiceFormat</code> programmatically, as in the
  273. * above example, or by using a pattern. See {@link ChoiceFormat}
  274. * for more information.
  275. * <blockquote><pre>
  276. * form.applyPattern(
  277. * "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
  278. * </pre></blockquote>
  279. *
  280. * <p>
  281. * <strong>Note:</strong> As we see above, the string produced
  282. * by a <code>ChoiceFormat</code> in <code>MessageFormat</code> is treated specially;
  283. * occurences of '{' are used to indicated subformats, and cause recursion.
  284. * If you create both a <code>MessageFormat</code> and <code>ChoiceFormat</code>
  285. * programmatically (instead of using the string patterns), then be careful not to
  286. * produce a format that recurses on itself, which will cause an infinite loop.
  287. * <p>
  288. * When a single argument is parsed more than once in the string, the last match
  289. * will be the final result of the parsing. For example,
  290. * <blockquote><pre>
  291. * MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
  292. * Object[] objs = {new Double(3.1415)};
  293. * String result = mf.format( objs );
  294. * // result now equals "3.14, 3.1"
  295. * objs = null;
  296. * objs = mf.parse(result, new ParsePosition(0));
  297. * // objs now equals {new Double(3.1)}
  298. * </pre></blockquote>
  299. *
  300. * <p>
  301. * Likewise, parsing with a MessageFormat object using patterns containing
  302. * multiple occurences of the same argument would return the last match. For
  303. * example,
  304. * <blockquote><pre>
  305. * MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
  306. * String forParsing = "x, y, z";
  307. * Object[] objs = mf.parse(forParsing, new ParsePosition(0));
  308. * // result now equals {new String("z")}
  309. * </pre></blockquote>
  310. *
  311. * <h4><a name="synchronization">Synchronization</a></h4>
  312. *
  313. * <p>
  314. * Message formats are not synchronized.
  315. * It is recommended to create separate format instances for each thread.
  316. * If multiple threads access a format concurrently, it must be synchronized
  317. * externally.
  318. *
  319. * @see java.util.Locale
  320. * @see Format
  321. * @see NumberFormat
  322. * @see DecimalFormat
  323. * @see ChoiceFormat
  324. * @version 1.56, 12/19/03
  325. * @author Mark Davis
  326. */
  327. public class MessageFormat extends Format {
  328. private static final long serialVersionUID = 6479157306784022952L;
  329. /**
  330. * Constructs a MessageFormat for the default locale and the
  331. * specified pattern.
  332. * The constructor first sets the locale, then parses the pattern and
  333. * creates a list of subformats for the format elements contained in it.
  334. * Patterns and their interpretation are specified in the
  335. * <a href="#patterns">class description</a>.
  336. *
  337. * @param pattern the pattern for this message format
  338. * @exception IllegalArgumentException if the pattern is invalid
  339. */
  340. public MessageFormat(String pattern) {
  341. this.locale = Locale.getDefault();
  342. applyPattern(pattern);
  343. }
  344. /**
  345. * Constructs a MessageFormat for the specified locale and
  346. * pattern.
  347. * The constructor first sets the locale, then parses the pattern and
  348. * creates a list of subformats for the format elements contained in it.
  349. * Patterns and their interpretation are specified in the
  350. * <a href="#patterns">class description</a>.
  351. *
  352. * @param pattern the pattern for this message format
  353. * @param locale the locale for this message format
  354. * @exception IllegalArgumentException if the pattern is invalid
  355. * @since 1.4
  356. */
  357. public MessageFormat(String pattern, Locale locale) {
  358. this.locale = locale;
  359. applyPattern(pattern);
  360. }
  361. /**
  362. * Sets the locale to be used when creating or comparing subformats.
  363. * This affects subsequent calls to the {@link #applyPattern applyPattern}
  364. * and {@link #toPattern toPattern} methods as well as to the
  365. * <code>format</code> and
  366. * {@link #formatToCharacterIterator formatToCharacterIterator} methods.
  367. *
  368. * @param locale the locale to be used when creating or comparing subformats
  369. */
  370. public void setLocale(Locale locale) {
  371. this.locale = locale;
  372. }
  373. /**
  374. * Gets the locale that's used when creating or comparing subformats.
  375. *
  376. * @return the locale used when creating or comparing subformats
  377. */
  378. public Locale getLocale() {
  379. return locale;
  380. }
  381. /**
  382. * Sets the pattern used by this message format.
  383. * The method parses the pattern and creates a list of subformats
  384. * for the format elements contained in it.
  385. * Patterns and their interpretation are specified in the
  386. * <a href="#patterns">class description</a>.
  387. *
  388. * @param pattern the pattern for this message format
  389. * @exception IllegalArgumentException if the pattern is invalid
  390. */
  391. public void applyPattern(String pattern) {
  392. StringBuffer[] segments = new StringBuffer[4];
  393. for (int i = 0; i < segments.length; ++i) {
  394. segments[i] = new StringBuffer();
  395. }
  396. int part = 0;
  397. int formatNumber = 0;
  398. boolean inQuote = false;
  399. int braceStack = 0;
  400. maxOffset = -1;
  401. for (int i = 0; i < pattern.length(); ++i) {
  402. char ch = pattern.charAt(i);
  403. if (part == 0) {
  404. if (ch == '\'') {
  405. if (i + 1 < pattern.length()
  406. && pattern.charAt(i+1) == '\'') {
  407. segments[part].append(ch); // handle doubles
  408. ++i;
  409. } else {
  410. inQuote = !inQuote;
  411. }
  412. } else if (ch == '{' && !inQuote) {
  413. part = 1;
  414. } else {
  415. segments[part].append(ch);
  416. }
  417. } else if (inQuote) { // just copy quotes in parts
  418. segments[part].append(ch);
  419. if (ch == '\'') {
  420. inQuote = false;
  421. }
  422. } else {
  423. switch (ch) {
  424. case ',':
  425. if (part < 3)
  426. part += 1;
  427. else
  428. segments[part].append(ch);
  429. break;
  430. case '{':
  431. ++braceStack;
  432. segments[part].append(ch);
  433. break;
  434. case '}':
  435. if (braceStack == 0) {
  436. part = 0;
  437. makeFormat(i, formatNumber, segments);
  438. formatNumber++;
  439. } else {
  440. --braceStack;
  441. segments[part].append(ch);
  442. }
  443. break;
  444. case '\'':
  445. inQuote = true;
  446. // fall through, so we keep quotes in other parts
  447. default:
  448. segments[part].append(ch);
  449. break;
  450. }
  451. }
  452. }
  453. if (braceStack == 0 && part != 0) {
  454. maxOffset = -1;
  455. throw new IllegalArgumentException("Unmatched braces in the pattern.");
  456. }
  457. this.pattern = segments[0].toString();
  458. }
  459. /**
  460. * Returns a pattern representing the current state of the message format.
  461. * The string is constructed from internal information and therefore
  462. * does not necessarily equal the previously applied pattern.
  463. *
  464. * @return a pattern representing the current state of the message format
  465. */
  466. public String toPattern() {
  467. // later, make this more extensible
  468. int lastOffset = 0;
  469. StringBuffer result = new StringBuffer();
  470. for (int i = 0; i <= maxOffset; ++i) {
  471. copyAndFixQuotes(pattern, lastOffset, offsets[i],result);
  472. lastOffset = offsets[i];
  473. result.append('{');
  474. result.append(argumentNumbers[i]);
  475. if (formats[i] == null) {
  476. // do nothing, string format
  477. } else if (formats[i] instanceof DecimalFormat) {
  478. if (formats[i].equals(NumberFormat.getInstance(locale))) {
  479. result.append(",number");
  480. } else if (formats[i].equals(NumberFormat.getCurrencyInstance(locale))) {
  481. result.append(",number,currency");
  482. } else if (formats[i].equals(NumberFormat.getPercentInstance(locale))) {
  483. result.append(",number,percent");
  484. } else if (formats[i].equals(NumberFormat.getIntegerInstance(locale))) {
  485. result.append(",number,integer");
  486. } else {
  487. result.append(",number," +
  488. ((DecimalFormat)formats[i]).toPattern());
  489. }
  490. } else if (formats[i] instanceof SimpleDateFormat) {
  491. if (formats[i].equals(DateFormat.getDateInstance(
  492. DateFormat.DEFAULT,locale))) {
  493. result.append(",date");
  494. } else if (formats[i].equals(DateFormat.getDateInstance(
  495. DateFormat.SHORT,locale))) {
  496. result.append(",date,short");
  497. } else if (formats[i].equals(DateFormat.getDateInstance(
  498. DateFormat.DEFAULT,locale))) {
  499. result.append(",date,medium");
  500. } else if (formats[i].equals(DateFormat.getDateInstance(
  501. DateFormat.LONG,locale))) {
  502. result.append(",date,long");
  503. } else if (formats[i].equals(DateFormat.getDateInstance(
  504. DateFormat.FULL,locale))) {
  505. result.append(",date,full");
  506. } else if (formats[i].equals(DateFormat.getTimeInstance(
  507. DateFormat.DEFAULT,locale))) {
  508. result.append(",time");
  509. } else if (formats[i].equals(DateFormat.getTimeInstance(
  510. DateFormat.SHORT,locale))) {
  511. result.append(",time,short");
  512. } else if (formats[i].equals(DateFormat.getTimeInstance(
  513. DateFormat.DEFAULT,locale))) {
  514. result.append(",time,medium");
  515. } else if (formats[i].equals(DateFormat.getTimeInstance(
  516. DateFormat.LONG,locale))) {
  517. result.append(",time,long");
  518. } else if (formats[i].equals(DateFormat.getTimeInstance(
  519. DateFormat.FULL,locale))) {
  520. result.append(",time,full");
  521. } else {
  522. result.append(",date,"
  523. + ((SimpleDateFormat)formats[i]).toPattern());
  524. }
  525. } else if (formats[i] instanceof ChoiceFormat) {
  526. result.append(",choice,"
  527. + ((ChoiceFormat)formats[i]).toPattern());
  528. } else {
  529. //result.append(", unknown");
  530. }
  531. result.append('}');
  532. }
  533. copyAndFixQuotes(pattern, lastOffset, pattern.length(), result);
  534. return result.toString();
  535. }
  536. /**
  537. * Sets the formats to use for the values passed into
  538. * <code>format</code> methods or returned from <code>parse</code>
  539. * methods. The indices of elements in <code>newFormats</code>
  540. * correspond to the argument indices used in the previously set
  541. * pattern string.
  542. * The order of formats in <code>newFormats</code> thus corresponds to
  543. * the order of elements in the <code>arguments</code> array passed
  544. * to the <code>format</code> methods or the result array returned
  545. * by the <code>parse</code> methods.
  546. * <p>
  547. * If an argument index is used for more than one format element
  548. * in the pattern string, then the corresponding new format is used
  549. * for all such format elements. If an argument index is not used
  550. * for any format element in the pattern string, then the
  551. * corresponding new format is ignored. If fewer formats are provided
  552. * than needed, then only the formats for argument indices less
  553. * than <code>newFormats.length</code> are replaced.
  554. *
  555. * @param newFormats the new formats to use
  556. * @exception NullPointerException if <code>newFormats</code> is null
  557. * @since 1.4
  558. */
  559. public void setFormatsByArgumentIndex(Format[] newFormats) {
  560. for (int i = 0; i <= maxOffset; i++) {
  561. int j = argumentNumbers[i];
  562. if (j < newFormats.length) {
  563. formats[i] = newFormats[j];
  564. }
  565. }
  566. }
  567. /**
  568. * Sets the formats to use for the format elements in the
  569. * previously set pattern string.
  570. * The order of formats in <code>newFormats</code> corresponds to
  571. * the order of format elements in the pattern string.
  572. * <p>
  573. * If more formats are provided than needed by the pattern string,
  574. * the remaining ones are ignored. If fewer formats are provided
  575. * than needed, then only the first <code>newFormats.length</code>
  576. * formats are replaced.
  577. * <p>
  578. * Since the order of format elements in a pattern string often
  579. * changes during localization, it is generally better to use the
  580. * {@link #setFormatsByArgumentIndex setFormatsByArgumentIndex}
  581. * method, which assumes an order of formats corresponding to the
  582. * order of elements in the <code>arguments</code> array passed to
  583. * the <code>format</code> methods or the result array returned by
  584. * the <code>parse</code> methods.
  585. *
  586. * @param newFormats the new formats to use
  587. * @exception NullPointerException if <code>newFormats</code> is null
  588. */
  589. public void setFormats(Format[] newFormats) {
  590. int runsToCopy = newFormats.length;
  591. if (runsToCopy > maxOffset + 1) {
  592. runsToCopy = maxOffset + 1;
  593. }
  594. for (int i = 0; i < runsToCopy; i++) {
  595. formats[i] = newFormats[i];
  596. }
  597. }
  598. /**
  599. * Sets the format to use for the format elements within the
  600. * previously set pattern string that use the given argument
  601. * index.
  602. * The argument index is part of the format element definition and
  603. * represents an index into the <code>arguments</code> array passed
  604. * to the <code>format</code> methods or the result array returned
  605. * by the <code>parse</code> methods.
  606. * <p>
  607. * If the argument index is used for more than one format element
  608. * in the pattern string, then the new format is used for all such
  609. * format elements. If the argument index is not used for any format
  610. * element in the pattern string, then the new format is ignored.
  611. *
  612. * @param argumentIndex the argument index for which to use the new format
  613. * @param newFormat the new format to use
  614. * @since 1.4
  615. */
  616. public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) {
  617. for (int j = 0; j <= maxOffset; j++) {
  618. if (argumentNumbers[j] == argumentIndex) {
  619. formats[j] = newFormat;
  620. }
  621. }
  622. }
  623. /**
  624. * Sets the format to use for the format element with the given
  625. * format element index within the previously set pattern string.
  626. * The format element index is the zero-based number of the format
  627. * element counting from the start of the pattern string.
  628. * <p>
  629. * Since the order of format elements in a pattern string often
  630. * changes during localization, it is generally better to use the
  631. * {@link #setFormatByArgumentIndex setFormatByArgumentIndex}
  632. * method, which accesses format elements based on the argument
  633. * index they specify.
  634. *
  635. * @param formatElementIndex the index of a format element within the pattern
  636. * @param newFormat the format to use for the specified format element
  637. * @exception ArrayIndexOutOfBoundsException if formatElementIndex is equal to or
  638. * larger than the number of format elements in the pattern string
  639. */
  640. public void setFormat(int formatElementIndex, Format newFormat) {
  641. formats[formatElementIndex] = newFormat;
  642. }
  643. /**
  644. * Gets the formats used for the values passed into
  645. * <code>format</code> methods or returned from <code>parse</code>
  646. * methods. The indices of elements in the returned array
  647. * correspond to the argument indices used in the previously set
  648. * pattern string.
  649. * The order of formats in the returned array thus corresponds to
  650. * the order of elements in the <code>arguments</code> array passed
  651. * to the <code>format</code> methods or the result array returned
  652. * by the <code>parse</code> methods.
  653. * <p>
  654. * If an argument index is used for more than one format element
  655. * in the pattern string, then the format used for the last such
  656. * format element is returned in the array. If an argument index
  657. * is not used for any format element in the pattern string, then
  658. * null is returned in the array.
  659. *
  660. * @return the formats used for the arguments within the pattern
  661. * @since 1.4
  662. */
  663. public Format[] getFormatsByArgumentIndex() {
  664. int maximumArgumentNumber = -1;
  665. for (int i = 0; i <= maxOffset; i++) {
  666. if (argumentNumbers[i] > maximumArgumentNumber) {
  667. maximumArgumentNumber = argumentNumbers[i];
  668. }
  669. }
  670. Format[] resultArray = new Format[maximumArgumentNumber + 1];
  671. for (int i = 0; i <= maxOffset; i++) {
  672. resultArray[argumentNumbers[i]] = formats[i];
  673. }
  674. return resultArray;
  675. }
  676. /**
  677. * Gets the formats used for the format elements in the
  678. * previously set pattern string.
  679. * The order of formats in the returned array corresponds to
  680. * the order of format elements in the pattern string.
  681. * <p>
  682. * Since the order of format elements in a pattern string often
  683. * changes during localization, it's generally better to use the
  684. * {@link #getFormatsByArgumentIndex getFormatsByArgumentIndex}
  685. * method, which assumes an order of formats corresponding to the
  686. * order of elements in the <code>arguments</code> array passed to
  687. * the <code>format</code> methods or the result array returned by
  688. * the <code>parse</code> methods.
  689. *
  690. * @return the formats used for the format elements in the pattern
  691. */
  692. public Format[] getFormats() {
  693. Format[] resultArray = new Format[maxOffset + 1];
  694. System.arraycopy(formats, 0, resultArray, 0, maxOffset + 1);
  695. return resultArray;
  696. }
  697. /**
  698. * Formats an array of objects and appends the <code>MessageFormat</code>'s
  699. * pattern, with format elements replaced by the formatted objects, to the
  700. * provided <code>StringBuffer</code>.
  701. * <p>
  702. * The text substituted for the individual format elements is derived from
  703. * the current subformat of the format element and the
  704. * <code>arguments</code> element at the format element's argument index
  705. * as indicated by the first matching line of the following table. An
  706. * argument is <i>unavailable</i> if <code>arguments</code> is
  707. * <code>null</code> or has fewer than argumentIndex+1 elements.
  708. * <p>
  709. * <table border=1 summary="Examples of subformat,argument,and formatted text">
  710. * <tr>
  711. * <th>Subformat
  712. * <th>Argument
  713. * <th>Formatted Text
  714. * <tr>
  715. * <td><i>any</i>
  716. * <td><i>unavailable</i>
  717. * <td><code>"{" + argumentIndex + "}"</code>
  718. * <tr>
  719. * <td><i>any</i>
  720. * <td><code>null</code>
  721. * <td><code>"null"</code>
  722. * <tr>
  723. * <td><code>instanceof ChoiceFormat</code>
  724. * <td><i>any</i>
  725. * <td><code>subformat.format(argument).indexOf('{') >= 0 ?<br>
  726. * (new MessageFormat(subformat.format(argument), getLocale())).format(argument) :
  727. * subformat.format(argument)</code>
  728. * <tr>
  729. * <td><code>!= null</code>
  730. * <td><i>any</i>
  731. * <td><code>subformat.format(argument)</code>
  732. * <tr>
  733. * <td><code>null</code>
  734. * <td><code>instanceof Number</code>
  735. * <td><code>NumberFormat.getInstance(getLocale()).format(argument)</code>
  736. * <tr>
  737. * <td><code>null</code>
  738. * <td><code>instanceof Date</code>
  739. * <td><code>DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument)</code>
  740. * <tr>
  741. * <td><code>null</code>
  742. * <td><code>instanceof String</code>
  743. * <td><code>argument</code>
  744. * <tr>
  745. * <td><code>null</code>
  746. * <td><i>any</i>
  747. * <td><code>argument.toString()</code>
  748. * </table>
  749. * <p>
  750. * If <code>pos</code> is non-null, and refers to
  751. * <code>Field.ARGUMENT</code>, the location of the first formatted
  752. * string will be returned.
  753. *
  754. * @param arguments an array of objects to be formatted and substituted.
  755. * @param result where text is appended.
  756. * @param pos On input: an alignment field, if desired.
  757. * On output: the offsets of the alignment field.
  758. * @exception IllegalArgumentException if an argument in the
  759. * <code>arguments</code> array is not of the type
  760. * expected by the format element(s) that use it.
  761. */
  762. public final StringBuffer format(Object[] arguments, StringBuffer result,
  763. FieldPosition pos)
  764. {
  765. return subformat(arguments, result, pos, null);
  766. }
  767. /**
  768. * Creates a MessageFormat with the given pattern and uses it
  769. * to format the given arguments. This is equivalent to
  770. * <blockquote>
  771. * <code>(new {@link #MessageFormat(String) MessageFormat}(pattern)).{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
  772. * </blockquote>
  773. *
  774. * @exception IllegalArgumentException if the pattern is invalid,
  775. * or if an argument in the <code>arguments</code> array
  776. * is not of the type expected by the format element(s)
  777. * that use it.
  778. */
  779. public static String format(String pattern, Object ... arguments) {
  780. MessageFormat temp = new MessageFormat(pattern);
  781. return temp.format(arguments);
  782. }
  783. // Overrides
  784. /**
  785. * Formats an array of objects and appends the <code>MessageFormat</code>'s
  786. * pattern, with format elements replaced by the formatted objects, to the
  787. * provided <code>StringBuffer</code>.
  788. * This is equivalent to
  789. * <blockquote>
  790. * <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}((Object[]) arguments, result, pos)</code>
  791. * </blockquote>
  792. *
  793. * @param arguments an array of objects to be formatted and substituted.
  794. * @param result where text is appended.
  795. * @param pos On input: an alignment field, if desired.
  796. * On output: the offsets of the alignment field.
  797. * @exception IllegalArgumentException if an argument in the
  798. * <code>arguments</code> array is not of the type
  799. * expected by the format element(s) that use it.
  800. */
  801. public final StringBuffer format(Object arguments, StringBuffer result,
  802. FieldPosition pos)
  803. {
  804. return subformat((Object[]) arguments, result, pos, null);
  805. }
  806. /**
  807. * Formats an array of objects and inserts them into the
  808. * <code>MessageFormat</code>'s pattern, producing an
  809. * <code>AttributedCharacterIterator</code>.
  810. * You can use the returned <code>AttributedCharacterIterator</code>
  811. * to build the resulting String, as well as to determine information
  812. * about the resulting String.
  813. * <p>
  814. * The text of the returned <code>AttributedCharacterIterator</code> is
  815. * the same that would be returned by
  816. * <blockquote>
  817. * <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
  818. * </blockquote>
  819. * <p>
  820. * In addition, the <code>AttributedCharacterIterator</code> contains at
  821. * least attributes indicating where text was generated from an
  822. * argument in the <code>arguments</code> array. The keys of these attributes are of
  823. * type <code>MessageFormat.Field</code>, their values are
  824. * <code>Integer</code> objects indicating the index in the <code>arguments</code>
  825. * array of the argument from which the text was generated.
  826. * <p>
  827. * The attributes/value from the underlying <code>Format</code>
  828. * instances that <code>MessageFormat</code> uses will also be
  829. * placed in the resulting <code>AttributedCharacterIterator</code>.
  830. * This allows you to not only find where an argument is placed in the
  831. * resulting String, but also which fields it contains in turn.
  832. *
  833. * @param arguments an array of objects to be formatted and substituted.
  834. * @return AttributedCharacterIterator describing the formatted value.
  835. * @exception NullPointerException if <code>arguments</code> is null.
  836. * @exception IllegalArgumentException if an argument in the
  837. * <code>arguments</code> array is not of the type
  838. * expected by the format element(s) that use it.
  839. * @since 1.4
  840. */
  841. public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
  842. StringBuffer result = new StringBuffer();
  843. ArrayList iterators = new ArrayList();
  844. if (arguments == null) {
  845. throw new NullPointerException(
  846. "formatToCharacterIterator must be passed non-null object");
  847. }
  848. subformat((Object[]) arguments, result, null, iterators);
  849. if (iterators.size() == 0) {
  850. return createAttributedCharacterIterator("");
  851. }
  852. return createAttributedCharacterIterator(
  853. (AttributedCharacterIterator[])iterators.toArray(
  854. new AttributedCharacterIterator[iterators.size()]));
  855. }
  856. /**
  857. * Parses the string.
  858. *
  859. * <p>Caveats: The parse may fail in a number of circumstances.
  860. * For example:
  861. * <ul>
  862. * <li>If one of the arguments does not occur in the pattern.
  863. * <li>If the format of an argument loses information, such as
  864. * with a choice format where a large number formats to "many".
  865. * <li>Does not yet handle recursion (where
  866. * the substituted strings contain {n} references.)
  867. * <li>Will not always find a match (or the correct match)
  868. * if some part of the parse is ambiguous.
  869. * For example, if the pattern "{1},{2}" is used with the
  870. * string arguments {"a,b", "c"}, it will format as "a,b,c".
  871. * When the result is parsed, it will return {"a", "b,c"}.
  872. * <li>If a single argument is parsed more than once in the string,
  873. * then the later parse wins.
  874. * </ul>
  875. * When the parse fails, use ParsePosition.getErrorIndex() to find out
  876. * where in the string did the parsing failed. The returned error
  877. * index is the starting offset of the sub-patterns that the string
  878. * is comparing with. For example, if the parsing string "AAA {0} BBB"
  879. * is comparing against the pattern "AAD {0} BBB", the error index is
  880. * 0. When an error occurs, the call to this method will return null.
  881. * If the source is null, return an empty array.
  882. */
  883. public Object[] parse(String source, ParsePosition pos) {
  884. if (source == null) {
  885. Object[] empty = {};
  886. return empty;
  887. }
  888. int maximumArgumentNumber = -1;
  889. for (int i = 0; i <= maxOffset; i++) {
  890. if (argumentNumbers[i] > maximumArgumentNumber) {
  891. maximumArgumentNumber = argumentNumbers[i];
  892. }
  893. }
  894. Object[] resultArray = new Object[maximumArgumentNumber + 1];
  895. int patternOffset = 0;
  896. int sourceOffset = pos.index;
  897. ParsePosition tempStatus = new ParsePosition(0);
  898. for (int i = 0; i <= maxOffset; ++i) {
  899. // match up to format
  900. int len = offsets[i] - patternOffset;
  901. if (len == 0 || pattern.regionMatches(patternOffset,
  902. source, sourceOffset, len)) {
  903. sourceOffset += len;
  904. patternOffset += len;
  905. } else {
  906. pos.errorIndex = sourceOffset;
  907. return null; // leave index as is to signal error
  908. }
  909. // now use format
  910. if (formats[i] == null) { // string format
  911. // if at end, use longest possible match
  912. // otherwise uses first match to intervening string
  913. // does NOT recursively try all possibilities
  914. int tempLength = (i != maxOffset) ? offsets[i+1] : pattern.length();
  915. int next;
  916. if (patternOffset >= tempLength) {
  917. next = source.length();
  918. }else{
  919. next = source.indexOf( pattern.substring(patternOffset,tempLength), sourceOffset);
  920. }
  921. if (next < 0) {
  922. pos.errorIndex = sourceOffset;
  923. return null; // leave index as is to signal error
  924. } else {
  925. String strValue= source.substring(sourceOffset,next);
  926. if (!strValue.equals("{"+argumentNumbers[i]+"}"))
  927. resultArray[argumentNumbers[i]]
  928. = source.substring(sourceOffset,next);
  929. sourceOffset = next;
  930. }
  931. } else {
  932. tempStatus.index = sourceOffset;
  933. resultArray[argumentNumbers[i]]
  934. = formats[i].parseObject(source,tempStatus);
  935. if (tempStatus.index == sourceOffset) {
  936. pos.errorIndex = sourceOffset;
  937. return null; // leave index as is to signal error
  938. }
  939. sourceOffset = tempStatus.index; // update
  940. }
  941. }
  942. int len = pattern.length() - patternOffset;
  943. if (len == 0 || pattern.regionMatches(patternOffset,
  944. source, sourceOffset, len)) {
  945. pos.index = sourceOffset + len;
  946. } else {
  947. pos.errorIndex = sourceOffset;
  948. return null; // leave index as is to signal error
  949. }
  950. return resultArray;
  951. }
  952. /**
  953. * Parses text from the beginning of the given string to produce an object
  954. * array.
  955. * The method may not use the entire text of the given string.
  956. * <p>
  957. * See the {@link #parse(String, ParsePosition)} method for more information
  958. * on message parsing.
  959. *
  960. * @param source A <code>String</code> whose beginning should be parsed.
  961. * @return An <code>Object</code> array parsed from the string.
  962. * @exception ParseException if the beginning of the specified string
  963. * cannot be parsed.
  964. */
  965. public Object[] parse(String source) throws ParseException {
  966. ParsePosition pos = new ParsePosition(0);
  967. Object[] result = parse(source, pos);
  968. if (pos.index == 0) // unchanged, returned object is null
  969. throw new ParseException("MessageFormat parse error!", pos.errorIndex);
  970. return result;
  971. }
  972. /**
  973. * Parses text from a string to produce an object array.
  974. * <p>
  975. * The method attempts to parse text starting at the index given by
  976. * <code>pos</code>.
  977. * If parsing succeeds, then the index of <code>pos</code> is updated
  978. * to the index after the last character used (parsing does not necessarily
  979. * use all characters up to the end of the string), and the parsed
  980. * object array is returned. The updated <code>pos</code> can be used to
  981. * indicate the starting point for the next call to this method.
  982. * If an error occurs, then the index of <code>pos</code> is not
  983. * changed, the error index of <code>pos</code> is set to the index of
  984. * the character where the error occurred, and null is returned.
  985. * <p>
  986. * See the {@link #parse(String, ParsePosition)} method for more information
  987. * on message parsing.
  988. *
  989. * @param source A <code>String</code>, part of which should be parsed.
  990. * @param pos A <code>ParsePosition</code> object with index and error
  991. * index information as described above.
  992. * @return An <code>Object</code> array parsed from the string. In case of
  993. * error, returns null.
  994. * @exception NullPointerException if <code>pos</code> is null.
  995. */
  996. public Object parseObject(String source, ParsePosition pos) {
  997. return parse(source, pos);
  998. }
  999. /**
  1000. * Creates and returns a copy of this object.
  1001. *
  1002. * @return a clone of this instance.
  1003. */
  1004. public Object clone() {
  1005. MessageFormat other = (MessageFormat) super.clone();
  1006. // clone arrays. Can't do with utility because of bug in Cloneable
  1007. other.formats = (Format[]) formats.clone(); // shallow clone
  1008. for (int i = 0; i < formats.length; ++i) {
  1009. if (formats[i] != null)
  1010. other.formats[i] = (Format)formats[i].clone();
  1011. }
  1012. // for primitives or immutables, shallow clone is enough
  1013. other.offsets = (int[]) offsets.clone();
  1014. other.argumentNumbers = (int[]) argumentNumbers.clone();
  1015. return other;
  1016. }
  1017. /**
  1018. * Equality comparison between two message format objects
  1019. */
  1020. public boolean equals(Object obj) {
  1021. if (this == obj) // quick check
  1022. return true;
  1023. if (obj == null || getClass() != obj.getClass())
  1024. return false;
  1025. MessageFormat other = (MessageFormat) obj;
  1026. return (maxOffset == other.maxOffset
  1027. && pattern.equals(other.pattern)
  1028. && Utility.objectEquals(locale, other.locale) // does null check
  1029. && Utility.arrayEquals(offsets,other.offsets)
  1030. && Utility.arrayEquals(argumentNumbers,other.argumentNumbers)
  1031. && Utility.arrayEquals(formats,other.formats));
  1032. }
  1033. /**
  1034. * Generates a hash code for the message format object.
  1035. */
  1036. public int hashCode() {
  1037. return pattern.hashCode(); // enough for reasonable distribution
  1038. }
  1039. /**
  1040. * Defines constants that are used as attribute keys in the
  1041. * <code>AttributedCharacterIterator</code> returned
  1042. * from <code>MessageFormat.formatToCharacterIterator</code>.
  1043. *
  1044. * @since 1.4
  1045. */
  1046. public static class Field extends Format.Field {
  1047. // Proclaim serial compatibility with 1.4 FCS
  1048. private static final long serialVersionUID = 7899943957617360810L;
  1049. /**
  1050. * Creates a Field with the specified name.
  1051. *
  1052. * @param name Name of the attribute
  1053. */
  1054. protected Field(String name) {
  1055. super(name);
  1056. }
  1057. /**
  1058. * Resolves instances being deserialized to the predefined constants.
  1059. *
  1060. * @throws InvalidObjectException if the constant could not be
  1061. * resolved.
  1062. * @return resolved MessageFormat.Field constant
  1063. */
  1064. protected Object readResolve() throws InvalidObjectException {
  1065. if (this.getClass() != MessageFormat.Field.class) {
  1066. throw new InvalidObjectException("subclass didn't correctly implement readResolve");
  1067. }
  1068. return ARGUMENT;
  1069. }
  1070. //
  1071. // The constants
  1072. //
  1073. /**
  1074. * Constant identifying a portion of a message that was generated
  1075. * from an argument passed into <code>formatToCharacterIterator</code>.
  1076. * The value associated with the key will be an <code>Integer</code>
  1077. * indicating the index in the <code>arguments</code> array of the
  1078. * argument from which the text was generated.
  1079. */
  1080. public final static Field ARGUMENT =
  1081. new Field("message argument field");
  1082. }
  1083. // ===========================privates============================
  1084. /**
  1085. * The locale to use for formatting numbers and dates.
  1086. * @serial
  1087. */
  1088. private Locale locale;
  1089. /**
  1090. * The string that the formatted values are to be plugged into. In other words, this
  1091. * is the pattern supplied on construction with all of the {} expressions taken out.
  1092. * @serial
  1093. */
  1094. private String pattern = "";
  1095. /** The initially expected number of subformats in the format */
  1096. private static final int INITIAL_FORMATS = 10;
  1097. /**
  1098. * An array of formatters, which are used to format the arguments.
  1099. * @serial
  1100. */
  1101. private Format[] formats = new Format[INITIAL_FORMATS];
  1102. /**
  1103. * The positions where the results of formatting each argument are to be inserted
  1104. * into the pattern.
  1105. * @serial
  1106. */
  1107. private int[] offsets = new int[INITIAL_FORMATS];
  1108. /**
  1109. * The argument numbers corresponding to each formatter. (The formatters are stored
  1110. * in the order they occur in the pattern, not in the order in which the arguments
  1111. * are specified.)
  1112. * @serial
  1113. */
  1114. private int[] argumentNumbers = new int[INITIAL_FORMATS];
  1115. /**
  1116. * One less than the number of entries in <code>offsets</code>. Can also be thought of
  1117. * as the index of the highest-numbered element in <code>offsets</code> that is being used.
  1118. * All of these arrays should have the same number of elements being used as <code>offsets</code>
  1119. * does, and so this variable suffices to tell us how many entries are in all of them.
  1120. * @serial
  1121. */
  1122. private int maxOffset = -1;
  1123. /**
  1124. * Internal routine used by format. If <code>characterIterators</code> is
  1125. * non-null, AttributedCharacterIterator will be created from the
  1126. * subformats as necessary. If <code>characterIterators</code> is null
  1127. * and <code>fp</code> is non-null and identifies
  1128. * <code>Field.MESSAGE_ARGUMENT</code>, the location of
  1129. * the first replaced argument will be set in it.
  1130. *
  1131. * @exception IllegalArgumentException if an argument in the
  1132. * <code>arguments</code> array is not of the type
  1133. * expected by the format element(s) that use it.
  1134. */
  1135. private StringBuffer subformat(Object[] arguments, StringBuffer result,
  1136. FieldPosition fp, List characterIterators) {
  1137. // note: this implementation assumes a fast substring & index.
  1138. // if this is not true, would be better to append chars one by one.
  1139. int lastOffset = 0;
  1140. int last = result.length();
  1141. for (int i = 0; i <= maxOffset; ++i) {
  1142. result.append(pattern.substring(lastOffset, offsets[i]));
  1143. lastOffset = offsets[i];
  1144. int argumentNumber = argumentNumbers[i];
  1145. if (arguments == null || argumentNumber >= arguments.length) {
  1146. result.append("{" + argumentNumber + "}");
  1147. continue;
  1148. }
  1149. // int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
  1150. if (false) { // if (argRecursion == 3){
  1151. // prevent loop!!!
  1152. result.append('\uFFFD');
  1153. } else {
  1154. Object obj = arguments[argumentNumber];
  1155. String arg = null;
  1156. Format subFormatter = null;
  1157. if (obj == null) {
  1158. arg = "null";
  1159. } else if (formats[i] != null) {
  1160. subFormatter = formats[i];
  1161. if (subFormatter instanceof ChoiceFormat) {
  1162. arg = formats[i].format(obj);
  1163. if (arg.indexOf('{') >= 0) {
  1164. subFormatter = new MessageFormat(arg, locale);
  1165. obj = arguments;
  1166. arg = null;
  1167. }
  1168. }
  1169. } else if (obj instanceof Number) {
  1170. // format number if can
  1171. subFormatter = NumberFormat.getInstance(locale);
  1172. } else if (obj instanceof Date) {
  1173. // format a Date if can
  1174. subFormatter = DateFormat.getDateTimeInstance(
  1175. DateFormat.SHORT, DateFormat.SHORT, locale);//fix
  1176. } else if (obj instanceof String) {
  1177. arg = (String) obj;
  1178. } else {
  1179. arg = obj.toString();
  1180. if (arg == null) arg = "null";
  1181. }
  1182. // At this point we are in two states, either subFormatter
  1183. // is non-null indicating we should format obj using it,
  1184. // or arg is non-null and we should use it as the value.
  1185. if (characterIterators != null) {
  1186. // If characterIterators is non-null, it indicates we need
  1187. // to get the CharacterIterator from the child formatter.
  1188. if (last != result.length()) {
  1189. characterIterators.add(
  1190. createAttributedCharacterIterator(result.substring
  1191. (last)));
  1192. last = result.length();
  1193. }
  1194. if (subFormatter != null) {
  1195. AttributedCharacterIterator subIterator =
  1196. subFormatter.formatToCharacterIterator(obj);
  1197. append(result, subIterator);
  1198. if (last != result.length()) {
  1199. characterIterators.add(
  1200. createAttributedCharacterIterator(
  1201. subIterator, Field.ARGUMENT,
  1202. new Integer(argumentNumber)));
  1203. last = result.length();
  1204. }
  1205. arg = null;
  1206. }
  1207. if (arg != null && arg.length() > 0) {
  1208. result.append(arg);
  1209. characterIterators.add(
  1210. createAttributedCharacterIterator(
  1211. arg, Field.ARGUMENT,
  1212. new Integer(argumentNumber)));
  1213. last = result.length();
  1214. }
  1215. }
  1216. else {
  1217. if (subFormatter != null) {
  1218. arg = subFormatter.format(obj);
  1219. }
  1220. last = result.length();
  1221. result.append(arg);
  1222. if (i == 0 && fp != null && Field.ARGUMENT.equals(
  1223. fp.getFieldAttribute())) {
  1224. fp.setBeginIndex(last);
  1225. fp.setEndIndex(result.length());
  1226. }
  1227. last = result.length();
  1228. }
  1229. }
  1230. }
  1231. result.append(pattern.substring(lastOffset, pattern.length()));
  1232. if (characterIterators != null && last != result.length()) {
  1233. characterIterators.add(createAttributedCharacterIterator(
  1234. result.substring(last)));
  1235. }
  1236. return result;
  1237. }
  1238. /**
  1239. * Convenience method to append all the characters in
  1240. * <code>iterator</code> to the StringBuffer <code>result</code>.
  1241. */
  1242. private void append(StringBuffer result, CharacterIterator iterator) {
  1243. if (iterator.first() != CharacterIterator.DONE) {
  1244. char aChar;
  1245. result.append(iterator.first());
  1246. while ((aChar = iterator.next()) != CharacterIterator.DONE) {
  1247. result.append(aChar);
  1248. }
  1249. }
  1250. }
  1251. private static final String[] typeList =
  1252. {"", "", "number", "", "date", "", "time", "", "choice"};
  1253. private static final String[] modifierList =
  1254. {"", "", "currency", "", "percent", "", "integer"};
  1255. private static final String[] dateModifierList =
  1256. {"", "", "short", "", "medium", "", "long", "", "full"};
  1257. private void makeFormat(int position, int offsetNumber,
  1258. StringBuffer[] segments)
  1259. {
  1260. // get the argument number
  1261. int argumentNumber;
  1262. try {
  1263. argumentNumber = Integer.parseInt(segments[1].toString()); // always unlocalized!
  1264. } catch (NumberFormatException e) {
  1265. throw new IllegalArgumentException("can't parse argument number " + segments[1]);
  1266. }
  1267. if (argumentNumber < 0) {
  1268. throw new IllegalArgumentException("negative argument number " + argumentNumber);
  1269. }
  1270. // resize format information arrays if necessary
  1271. if (offsetNumber >= formats.length) {
  1272. int newLength = formats.length * 2;
  1273. Format[] newFormats = new Format[newLength];
  1274. int[] newOffsets = new int[newLength];
  1275. int[] newArgumentNumbers = new int[newLength];
  1276. System.arraycopy(formats, 0, newFormats, 0, maxOffset + 1);
  1277. System.arraycopy(offsets, 0, newOffsets, 0, maxOffset + 1);
  1278. System.arraycopy(argumentNumbers, 0, newArgumentNumbers, 0, maxOffset + 1);
  1279. formats = newFormats;
  1280. offsets = newOffsets;
  1281. argumentNumbers = newArgumentNumbers;
  1282. }
  1283. int oldMaxOffset = maxOffset;
  1284. maxOffset = offsetNumber;
  1285. offsets[offsetNumber] = segments[0].length();
  1286. argumentNumbers[offsetNumber] = argumentNumber;
  1287. // now get the format
  1288. Format newFormat = null;
  1289. switch (findKeyword(segments[2].toString(), typeList)) {
  1290. case 0:
  1291. break;
  1292. case 1: case 2:// number
  1293. switch (findKeyword(segments[3].toString(), modifierList)) {
  1294. case 0: // default;
  1295. newFormat = NumberFormat.getInstance(locale);
  1296. break;
  1297. case 1: case 2:// currency
  1298. newFormat = NumberFormat.getCurrencyInstance(locale);
  1299. break;
  1300. case 3: case 4:// percent
  1301. newFormat = NumberFormat.getPercentInstance(locale);
  1302. break;
  1303. case 5: case 6:// integer
  1304. newFormat = NumberFormat.getIntegerInstance(locale);
  1305. break;
  1306. default: // pattern
  1307. newFormat = new DecimalFormat(segments[3].toString(), new DecimalFormatSymbols(locale));
  1308. break;
  1309. }
  1310. break;
  1311. case 3: case 4: // date
  1312. switch (findKeyword(segments[3].toString(), dateModifierList)) {
  1313. case 0: // default
  1314. newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
  1315. break;
  1316. case 1: case 2: // short
  1317. newFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
  1318. break;
  1319. case 3: case 4: // medium
  1320. newFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
  1321. break;
  1322. case 5: case 6: // long
  1323. newFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
  1324. break;
  1325. case 7: case 8: // full
  1326. newFormat = DateFormat.getDateInstance(DateFormat.FULL, locale);
  1327. break;
  1328. default:
  1329. newFormat = new SimpleDateFormat(segments[3].toString(), locale);
  1330. break;
  1331. }
  1332. break;
  1333. case 5: case 6:// time
  1334. switch (findKeyword(segments[3].toString(), dateModifierList)) {
  1335. case 0: // default
  1336. newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
  1337. break;
  1338. case 1: case 2: // short
  1339. newFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
  1340. break;
  1341. case 3: case 4: // medium
  1342. newFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
  1343. break;
  1344. case 5: case 6: // long
  1345. newFormat = DateFormat.getTimeInstance(DateFormat.LONG, locale);
  1346. break;
  1347. case 7: case 8: // full
  1348. newFormat = DateFormat.getTimeInstance(DateFormat.FULL, locale);
  1349. break;
  1350. default:
  1351. newFormat = new SimpleDateFormat(segments[3].toString(), locale);
  1352. break;
  1353. }
  1354. break;
  1355. case 7: case 8:// choice
  1356. try {
  1357. newFormat = new ChoiceFormat(segments[3].toString());
  1358. } catch (Exception e) {
  1359. maxOffset = oldMaxOffset;
  1360. throw new IllegalArgumentException(
  1361. "Choice Pattern incorrect");
  1362. }
  1363. break;
  1364. default:
  1365. maxOffset = oldMaxOffset;
  1366. throw new IllegalArgumentException("unknown format type at ");
  1367. }
  1368. formats[offsetNumber] = newFormat;
  1369. segments[1].setLength(0); // throw away other segments
  1370. segments[2].setLength(0);
  1371. segments[3].setLength(0);
  1372. }
  1373. private static final int findKeyword(String s, String[] list) {
  1374. s = s.trim().toLowerCase();
  1375. for (int i = 0; i < list.length; ++i) {
  1376. if (s.equals(list[i]))
  1377. return i;
  1378. }
  1379. return -1;
  1380. }
  1381. private static final void copyAndFixQuotes(
  1382. String source, int start, int end, StringBuffer target) {
  1383. for (int i = start; i < end; ++i) {
  1384. char ch = source.charAt(i);
  1385. if (ch == '{') {
  1386. target.append("'{'");
  1387. } else if (ch == '}') {
  1388. target.append("'}'");
  1389. } else if (ch == '\'') {
  1390. target.append("''");
  1391. } else {
  1392. target.append(ch);
  1393. }
  1394. }
  1395. }
  1396. /**
  1397. * After reading an object from the input stream, do a simple verification
  1398. * to maintain class invariants.
  1399. * @throws InvalidObjectException if the objects read from the stream is invalid.
  1400. */
  1401. private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  1402. in.defaultReadObject();
  1403. boolean isValid = maxOffset >= -1
  1404. && formats.length > maxOffset
  1405. && offsets.length > maxOffset
  1406. && argumentNumbers.length > maxOffset;
  1407. if (isValid) {
  1408. int lastOffset = pattern.length() + 1;
  1409. for (int i = maxOffset; i >= 0; --i) {
  1410. if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
  1411. isValid = false;
  1412. break;
  1413. } else {
  1414. lastOffset = offsets[i];
  1415. }
  1416. }
  1417. }
  1418. if (!isValid) {
  1419. throw new InvalidObjectException("Could not reconstruct MessageFormat from corrupt stream.");
  1420. }
  1421. }
  1422. }