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