MessageFormat.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. /* MessageFormat.java - Localized message formatting.
  2. Copyright (C) 1999, 2001, 2002, 2004, 2005, 2012 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.text;
  32. import gnu.java.lang.CPStringBuilder;
  33. import gnu.java.text.FormatCharacterIterator;
  34. import java.io.InvalidObjectException;
  35. import java.util.ArrayList;
  36. import java.util.Date;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Locale;
  40. public class MessageFormat extends Format
  41. {
  42. /**
  43. * @author Tom Tromey (tromey@cygnus.com)
  44. * @author Jorge Aliss (jaliss@hotmail.com)
  45. * @date March 3, 1999
  46. */
  47. /* Written using "Java Class Libraries", 2nd edition, plus online
  48. * API docs for JDK 1.2 from http://www.javasoft.com.
  49. * Status: Believed complete and correct to 1.2, except serialization.
  50. * and parsing.
  51. */
  52. private static final class MessageFormatElement
  53. {
  54. // Argument number.
  55. int argNumber;
  56. // Formatter to be used. This is the format set by setFormat.
  57. Format setFormat;
  58. // Formatter to be used based on the type.
  59. Format format;
  60. // Argument will be checked to make sure it is an instance of this
  61. // class.
  62. Class<?> formatClass;
  63. // Formatter type.
  64. String type;
  65. // Formatter style.
  66. String style;
  67. // Text to follow this element.
  68. String trailer;
  69. // Recompute the locale-based formatter.
  70. void setLocale (Locale loc)
  71. {
  72. if (type != null)
  73. {
  74. if (type.equals("number"))
  75. {
  76. formatClass = java.lang.Number.class;
  77. if (style == null)
  78. format = NumberFormat.getInstance(loc);
  79. else if (style.equals("currency"))
  80. format = NumberFormat.getCurrencyInstance(loc);
  81. else if (style.equals("percent"))
  82. format = NumberFormat.getPercentInstance(loc);
  83. else if (style.equals("integer"))
  84. format = NumberFormat.getIntegerInstance(loc);
  85. else
  86. {
  87. format = NumberFormat.getNumberInstance(loc);
  88. DecimalFormat df = (DecimalFormat) format;
  89. df.applyPattern(style);
  90. }
  91. }
  92. else if (type.equals("time") || type.equals("date"))
  93. {
  94. formatClass = java.util.Date.class;
  95. int val = DateFormat.DEFAULT;
  96. boolean styleIsPattern = false;
  97. if (style != null)
  98. {
  99. if (style.equals("short"))
  100. val = DateFormat.SHORT;
  101. else if (style.equals("medium"))
  102. val = DateFormat.MEDIUM;
  103. else if (style.equals("long"))
  104. val = DateFormat.LONG;
  105. else if (style.equals("full"))
  106. val = DateFormat.FULL;
  107. else
  108. styleIsPattern = true;
  109. }
  110. if (type.equals("time"))
  111. format = DateFormat.getTimeInstance(val, loc);
  112. else
  113. format = DateFormat.getDateInstance(val, loc);
  114. if (styleIsPattern)
  115. {
  116. SimpleDateFormat sdf = (SimpleDateFormat) format;
  117. sdf.applyPattern(style);
  118. }
  119. }
  120. else if (type.equals("choice"))
  121. {
  122. formatClass = java.lang.Number.class;
  123. if (style == null)
  124. throw new
  125. IllegalArgumentException ("style required for choice format");
  126. format = new ChoiceFormat (style);
  127. }
  128. }
  129. }
  130. }
  131. private static final long serialVersionUID = 6479157306784022952L;
  132. public static class Field extends Format.Field
  133. {
  134. static final long serialVersionUID = 7899943957617360810L;
  135. /**
  136. * This is the attribute set for all characters produced
  137. * by MessageFormat during a formatting.
  138. */
  139. public static final MessageFormat.Field ARGUMENT = new MessageFormat.Field("argument");
  140. // For deserialization
  141. private Field()
  142. {
  143. super("");
  144. }
  145. protected Field(String s)
  146. {
  147. super(s);
  148. }
  149. /**
  150. * invoked to resolve the true static constant by
  151. * comparing the deserialized object to know name.
  152. *
  153. * @return object constant
  154. */
  155. protected Object readResolve() throws InvalidObjectException
  156. {
  157. if (getName().equals(ARGUMENT.getName()))
  158. return ARGUMENT;
  159. throw new InvalidObjectException("no such MessageFormat field called " + getName());
  160. }
  161. }
  162. // Helper that returns the text up to the next format opener. The
  163. // text is put into BUFFER. Returns index of character after end of
  164. // string. Throws IllegalArgumentException on error.
  165. private static int scanString(String pat, int index, CPStringBuilder buffer)
  166. {
  167. int max = pat.length();
  168. buffer.setLength(0);
  169. boolean quoted = false;
  170. for (; index < max; ++index)
  171. {
  172. char c = pat.charAt(index);
  173. if (quoted)
  174. {
  175. // In a quoted context, a single quote ends the quoting.
  176. if (c == '\'')
  177. quoted = false;
  178. else
  179. buffer.append(c);
  180. }
  181. // Check for '', which is a single quote.
  182. else if (c == '\'' && index + 1 < max && pat.charAt(index + 1) == '\'')
  183. {
  184. buffer.append(c);
  185. ++index;
  186. }
  187. else if (c == '\'')
  188. {
  189. // Start quoting.
  190. quoted = true;
  191. }
  192. else if (c == '{')
  193. break;
  194. else
  195. buffer.append(c);
  196. }
  197. // Note that we explicitly allow an unterminated quote. This is
  198. // done for compatibility.
  199. return index;
  200. }
  201. // This helper retrieves a single part of a format element. Returns
  202. // the index of the terminating character.
  203. private static int scanFormatElement(String pat, int index,
  204. CPStringBuilder buffer, char term)
  205. {
  206. int max = pat.length();
  207. buffer.setLength(0);
  208. int brace_depth = 1;
  209. boolean quoted = false;
  210. for (; index < max; ++index)
  211. {
  212. char c = pat.charAt(index);
  213. // First see if we should turn off quoting.
  214. if (quoted)
  215. {
  216. if (c == '\'')
  217. quoted = false;
  218. // In both cases we fall through to inserting the
  219. // character here.
  220. }
  221. // See if we have just a plain quote to insert.
  222. else if (c == '\'' && index + 1 < max
  223. && pat.charAt(index + 1) == '\'')
  224. {
  225. buffer.append(c);
  226. ++index;
  227. }
  228. // See if quoting should turn on.
  229. else if (c == '\'')
  230. quoted = true;
  231. else if (c == '{')
  232. ++brace_depth;
  233. else if (c == '}')
  234. {
  235. if (--brace_depth == 0)
  236. break;
  237. }
  238. // Check for TERM after braces, because TERM might be `}'.
  239. else if (c == term)
  240. break;
  241. // All characters, including opening and closing quotes, are
  242. // inserted here.
  243. buffer.append(c);
  244. }
  245. return index;
  246. }
  247. // This is used to parse a format element and whatever non-format
  248. // text might trail it.
  249. private static int scanFormat(String pat, int index, CPStringBuilder buffer,
  250. List<MessageFormatElement> elts, Locale locale)
  251. {
  252. MessageFormatElement mfe = new MessageFormatElement ();
  253. elts.add(mfe);
  254. int max = pat.length();
  255. // Skip the opening `{'.
  256. ++index;
  257. // Fetch the argument number.
  258. index = scanFormatElement (pat, index, buffer, ',');
  259. try
  260. {
  261. mfe.argNumber = Integer.parseInt(buffer.toString());
  262. }
  263. catch (NumberFormatException nfx)
  264. {
  265. IllegalArgumentException iae = new IllegalArgumentException(pat);
  266. iae.initCause(nfx);
  267. throw iae;
  268. }
  269. // Extract the element format.
  270. if (index < max && pat.charAt(index) == ',')
  271. {
  272. index = scanFormatElement (pat, index + 1, buffer, ',');
  273. mfe.type = buffer.toString();
  274. // Extract the style.
  275. if (index < max && pat.charAt(index) == ',')
  276. {
  277. index = scanFormatElement (pat, index + 1, buffer, '}');
  278. mfe.style = buffer.toString ();
  279. }
  280. }
  281. // Advance past the last terminator.
  282. if (index >= max || pat.charAt(index) != '}')
  283. throw new IllegalArgumentException("Missing '}' at end of message format");
  284. ++index;
  285. // Now fetch trailing string.
  286. index = scanString (pat, index, buffer);
  287. mfe.trailer = buffer.toString ();
  288. mfe.setLocale(locale);
  289. return index;
  290. }
  291. /**
  292. * Applies the specified pattern to this MessageFormat.
  293. *
  294. * @param newPattern The Pattern
  295. */
  296. public void applyPattern (String newPattern)
  297. {
  298. pattern = newPattern;
  299. CPStringBuilder tempBuffer = new CPStringBuilder ();
  300. int index = scanString (newPattern, 0, tempBuffer);
  301. leader = tempBuffer.toString();
  302. List<MessageFormatElement> elts = new ArrayList<MessageFormatElement>();
  303. while (index < newPattern.length())
  304. index = scanFormat (newPattern, index, tempBuffer, elts, locale);
  305. elements = elts.toArray(new MessageFormatElement[elts.size()]);
  306. }
  307. /**
  308. * Overrides Format.clone()
  309. */
  310. public Object clone ()
  311. {
  312. MessageFormat c = (MessageFormat) super.clone ();
  313. c.elements = (MessageFormatElement[]) elements.clone ();
  314. return c;
  315. }
  316. /**
  317. * Overrides Format.equals(Object obj)
  318. */
  319. public boolean equals (Object obj)
  320. {
  321. if (! (obj instanceof MessageFormat))
  322. return false;
  323. MessageFormat mf = (MessageFormat) obj;
  324. return (pattern.equals(mf.pattern)
  325. && locale.equals(mf.locale));
  326. }
  327. /**
  328. * A convinience method to format patterns.
  329. *
  330. * @param arguments The array containing the objects to be formatted.
  331. */
  332. public AttributedCharacterIterator formatToCharacterIterator (Object arguments)
  333. {
  334. Object[] arguments_array = (Object[])arguments;
  335. FormatCharacterIterator iterator = new FormatCharacterIterator();
  336. formatInternal(arguments_array, new StringBuffer(), null, iterator);
  337. return iterator;
  338. }
  339. /**
  340. * A convinience method to format patterns.
  341. *
  342. * @param pattern The pattern used when formatting.
  343. * @param arguments The array containing the objects to be formatted.
  344. */
  345. public static String format (String pattern, Object... arguments)
  346. {
  347. MessageFormat mf = new MessageFormat (pattern);
  348. StringBuffer sb = new StringBuffer ();
  349. FieldPosition fp = new FieldPosition (NumberFormat.INTEGER_FIELD);
  350. return mf.formatInternal(arguments, sb, fp, null).toString();
  351. }
  352. /**
  353. * Returns the pattern with the formatted objects.
  354. *
  355. * @param arguments The array containing the objects to be formatted.
  356. * @param appendBuf The StringBuffer where the text is appened.
  357. * @param fp A FieldPosition object (it is ignored).
  358. */
  359. public final StringBuffer format (Object arguments[], StringBuffer appendBuf,
  360. FieldPosition fp)
  361. {
  362. return formatInternal(arguments, appendBuf, fp, null);
  363. }
  364. private StringBuffer formatInternal (Object arguments[],
  365. StringBuffer appendBuf,
  366. FieldPosition fp,
  367. FormatCharacterIterator output_iterator)
  368. {
  369. appendBuf.append(leader);
  370. if (output_iterator != null)
  371. output_iterator.append(leader);
  372. for (int i = 0; i < elements.length; ++i)
  373. {
  374. Object thisArg = null;
  375. boolean unavailable = false;
  376. if (arguments == null || elements[i].argNumber >= arguments.length)
  377. unavailable = true;
  378. else
  379. thisArg = arguments[elements[i].argNumber];
  380. AttributedCharacterIterator iterator = null;
  381. Format formatter = null;
  382. if (fp != null && i == fp.getField() && fp.getFieldAttribute() == Field.ARGUMENT)
  383. fp.setBeginIndex(appendBuf.length());
  384. if (unavailable)
  385. appendBuf.append("{" + elements[i].argNumber + "}");
  386. else
  387. {
  388. if (elements[i].setFormat != null)
  389. formatter = elements[i].setFormat;
  390. else if (elements[i].format != null)
  391. {
  392. if (elements[i].formatClass != null
  393. && ! elements[i].formatClass.isInstance(thisArg))
  394. throw new IllegalArgumentException("Wrong format class");
  395. formatter = elements[i].format;
  396. }
  397. else if (thisArg instanceof Number)
  398. formatter = NumberFormat.getInstance(locale);
  399. else if (thisArg instanceof Date)
  400. formatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
  401. else
  402. appendBuf.append(thisArg);
  403. }
  404. if (fp != null && fp.getField() == i && fp.getFieldAttribute() == Field.ARGUMENT)
  405. fp.setEndIndex(appendBuf.length());
  406. if (formatter != null)
  407. {
  408. // Special-case ChoiceFormat.
  409. if (formatter instanceof ChoiceFormat)
  410. {
  411. StringBuffer buf = new StringBuffer ();
  412. formatter.format(thisArg, buf, fp);
  413. MessageFormat mf = new MessageFormat ();
  414. mf.setLocale(locale);
  415. mf.applyPattern(buf.toString());
  416. mf.format(arguments, appendBuf, fp);
  417. }
  418. else
  419. {
  420. if (output_iterator != null)
  421. iterator = formatter.formatToCharacterIterator(thisArg);
  422. else
  423. formatter.format(thisArg, appendBuf, fp);
  424. }
  425. elements[i].format = formatter;
  426. }
  427. if (output_iterator != null)
  428. {
  429. HashMap<MessageFormat.Field, Integer> hash_argument =
  430. new HashMap<MessageFormat.Field, Integer>();
  431. int position = output_iterator.getEndIndex();
  432. hash_argument.put (MessageFormat.Field.ARGUMENT,
  433. Integer.valueOf(elements[i].argNumber));
  434. if (iterator != null)
  435. {
  436. output_iterator.append(iterator);
  437. output_iterator.addAttributes(hash_argument, position,
  438. output_iterator.getEndIndex());
  439. }
  440. else
  441. output_iterator.append(thisArg.toString(), hash_argument);
  442. output_iterator.append(elements[i].trailer);
  443. }
  444. appendBuf.append(elements[i].trailer);
  445. }
  446. return appendBuf;
  447. }
  448. /**
  449. * Returns the pattern with the formatted objects. The first argument
  450. * must be a array of Objects.
  451. * This is equivalent to format((Object[]) objectArray, appendBuf, fpos)
  452. *
  453. * @param objectArray The object array to be formatted.
  454. * @param appendBuf The StringBuffer where the text is appened.
  455. * @param fpos A FieldPosition object (it is ignored).
  456. */
  457. public final StringBuffer format (Object objectArray, StringBuffer appendBuf,
  458. FieldPosition fpos)
  459. {
  460. return format ((Object[])objectArray, appendBuf, fpos);
  461. }
  462. /**
  463. * Returns an array with the Formats for
  464. * the arguments.
  465. */
  466. public Format[] getFormats ()
  467. {
  468. Format[] f = new Format[elements.length];
  469. for (int i = elements.length - 1; i >= 0; --i)
  470. f[i] = elements[i].setFormat;
  471. return f;
  472. }
  473. /**
  474. * Returns the locale.
  475. */
  476. public Locale getLocale ()
  477. {
  478. return locale;
  479. }
  480. /**
  481. * Overrides Format.hashCode()
  482. */
  483. public int hashCode ()
  484. {
  485. // FIXME: not a very good hash.
  486. return pattern.hashCode() + locale.hashCode();
  487. }
  488. private MessageFormat ()
  489. {
  490. }
  491. /**
  492. * Creates a new MessageFormat object with
  493. * the specified pattern
  494. *
  495. * @param pattern The Pattern
  496. */
  497. public MessageFormat(String pattern)
  498. {
  499. this(pattern, Locale.getDefault());
  500. }
  501. /**
  502. * Creates a new MessageFormat object with
  503. * the specified pattern
  504. *
  505. * @param pattern The Pattern
  506. * @param locale The Locale to use
  507. *
  508. * @since 1.4
  509. */
  510. public MessageFormat(String pattern, Locale locale)
  511. {
  512. this.locale = locale;
  513. applyPattern (pattern);
  514. }
  515. /**
  516. * Parse a string <code>sourceStr</code> against the pattern specified
  517. * to the MessageFormat constructor.
  518. *
  519. * @param sourceStr the string to be parsed.
  520. * @param pos the current parse position (and eventually the error position).
  521. * @return the array of parsed objects sorted according to their argument number
  522. * in the pattern.
  523. */
  524. public Object[] parse (String sourceStr, ParsePosition pos)
  525. {
  526. // Check initial text.
  527. int index = pos.getIndex();
  528. if (! sourceStr.startsWith(leader, index))
  529. {
  530. pos.setErrorIndex(index);
  531. return null;
  532. }
  533. index += leader.length();
  534. ArrayList<Object> results = new ArrayList<Object>(elements.length);
  535. // Now check each format.
  536. for (int i = 0; i < elements.length; ++i)
  537. {
  538. Format formatter = null;
  539. if (elements[i].setFormat != null)
  540. formatter = elements[i].setFormat;
  541. else if (elements[i].format != null)
  542. formatter = elements[i].format;
  543. Object value = null;
  544. if (formatter instanceof ChoiceFormat)
  545. {
  546. // We must special-case a ChoiceFormat because it might
  547. // have recursive formatting.
  548. ChoiceFormat cf = (ChoiceFormat) formatter;
  549. String[] formats = (String[]) cf.getFormats();
  550. double[] limits = cf.getLimits();
  551. MessageFormat subfmt = new MessageFormat ();
  552. subfmt.setLocale(locale);
  553. ParsePosition subpos = new ParsePosition (index);
  554. int j;
  555. for (j = 0; value == null && j < limits.length; ++j)
  556. {
  557. subfmt.applyPattern(formats[j]);
  558. subpos.setIndex(index);
  559. value = subfmt.parse(sourceStr, subpos);
  560. }
  561. if (value != null)
  562. {
  563. index = subpos.getIndex();
  564. value = new Double (limits[j]);
  565. }
  566. }
  567. else if (formatter != null)
  568. {
  569. pos.setIndex(index);
  570. value = formatter.parseObject(sourceStr, pos);
  571. if (value != null)
  572. index = pos.getIndex();
  573. }
  574. else
  575. {
  576. // We have a String format. This can lose in a number
  577. // of ways, but we give it a shot.
  578. int next_index;
  579. if (elements[i].trailer.length() > 0)
  580. next_index = sourceStr.indexOf(elements[i].trailer, index);
  581. else
  582. next_index = sourceStr.length();
  583. if (next_index == -1)
  584. {
  585. pos.setErrorIndex(index);
  586. return null;
  587. }
  588. value = sourceStr.substring(index, next_index);
  589. index = next_index;
  590. }
  591. if (value == null
  592. || ! sourceStr.startsWith(elements[i].trailer, index))
  593. {
  594. pos.setErrorIndex(index);
  595. return null;
  596. }
  597. if (elements[i].argNumber >= results.size())
  598. {
  599. // Emulate padding behaviour of Vector.setSize() with ArrayList
  600. results.ensureCapacity(elements[i].argNumber + 1);
  601. for (int a = results.size(); a <= elements[i].argNumber; ++a)
  602. results.add(a, null);
  603. }
  604. results.set(elements[i].argNumber, value);
  605. index += elements[i].trailer.length();
  606. }
  607. return results.toArray(new Object[results.size()]);
  608. }
  609. public Object[] parse (String sourceStr) throws ParseException
  610. {
  611. ParsePosition pp = new ParsePosition (0);
  612. Object[] r = parse (sourceStr, pp);
  613. if (r == null)
  614. throw new ParseException ("couldn't parse string", pp.getErrorIndex());
  615. return r;
  616. }
  617. public Object parseObject (String sourceStr, ParsePosition pos)
  618. {
  619. return parse (sourceStr, pos);
  620. }
  621. /**
  622. * Sets the format for the argument at an specified
  623. * index.
  624. *
  625. * @param variableNum The index.
  626. * @param newFormat The Format object.
  627. */
  628. public void setFormat (int variableNum, Format newFormat)
  629. {
  630. elements[variableNum].setFormat = newFormat;
  631. }
  632. /**
  633. * Sets the formats for the arguments.
  634. *
  635. * @param newFormats An array of Format objects.
  636. */
  637. public void setFormats (Format[] newFormats)
  638. {
  639. if (newFormats.length < elements.length)
  640. throw new IllegalArgumentException("Not enough format objects");
  641. int len = Math.min(newFormats.length, elements.length);
  642. for (int i = 0; i < len; ++i)
  643. elements[i].setFormat = newFormats[i];
  644. }
  645. /**
  646. * Sets the locale.
  647. *
  648. * @param loc A Locale
  649. */
  650. public void setLocale (Locale loc)
  651. {
  652. locale = loc;
  653. if (elements != null)
  654. {
  655. for (int i = 0; i < elements.length; ++i)
  656. elements[i].setLocale(loc);
  657. }
  658. }
  659. /**
  660. * Returns the pattern.
  661. */
  662. public String toPattern ()
  663. {
  664. return pattern;
  665. }
  666. /**
  667. * Return the formatters used sorted by argument index. It uses the
  668. * internal table to fill in this array: if a format has been
  669. * set using <code>setFormat</code> or <code>setFormatByArgumentIndex</code>
  670. * then it returns it at the right index. If not it uses the detected
  671. * formatters during a <code>format</code> call. If nothing is known
  672. * about that argument index it just puts null at that position.
  673. * To get useful informations you may have to call <code>format</code>
  674. * at least once.
  675. *
  676. * @return an array of formatters sorted by argument index.
  677. */
  678. public Format[] getFormatsByArgumentIndex()
  679. {
  680. int argNumMax = 0;
  681. // First, find the greatest argument number.
  682. for (int i=0;i<elements.length;i++)
  683. if (elements[i].argNumber > argNumMax)
  684. argNumMax = elements[i].argNumber;
  685. Format[] formats = new Format[argNumMax];
  686. for (int i=0;i<elements.length;i++)
  687. {
  688. if (elements[i].setFormat != null)
  689. formats[elements[i].argNumber] = elements[i].setFormat;
  690. else if (elements[i].format != null)
  691. formats[elements[i].argNumber] = elements[i].format;
  692. }
  693. return formats;
  694. }
  695. /**
  696. * Set the format to used using the argument index number.
  697. *
  698. * @param argumentIndex the argument index.
  699. * @param newFormat the format to use for this argument.
  700. */
  701. public void setFormatByArgumentIndex(int argumentIndex,
  702. Format newFormat)
  703. {
  704. for (int i=0;i<elements.length;i++)
  705. {
  706. if (elements[i].argNumber == argumentIndex)
  707. elements[i].setFormat = newFormat;
  708. }
  709. }
  710. /**
  711. * Set the format for argument using a specified array of formatters
  712. * which is sorted according to the argument index. If the number of
  713. * elements in the array is fewer than the number of arguments only
  714. * the arguments specified by the array are touched.
  715. *
  716. * @param newFormats array containing the new formats to set.
  717. *
  718. * @throws NullPointerException if newFormats is null
  719. */
  720. public void setFormatsByArgumentIndex(Format[] newFormats)
  721. {
  722. for (int i=0;i<newFormats.length;i++)
  723. {
  724. // Nothing better than that can exist here.
  725. setFormatByArgumentIndex(i, newFormats[i]);
  726. }
  727. }
  728. // The pattern string.
  729. private String pattern;
  730. // The locale.
  731. private Locale locale;
  732. // Variables.
  733. private MessageFormatElement[] elements;
  734. // Leader text.
  735. private String leader;
  736. }