1. /*
  2. * @(#)Format.java 1.34 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.Serializable;
  21. /**
  22. * <code>Format</code> is an abstract base class for formatting locale-sensitive
  23. * information such as dates, messages, and numbers.
  24. *
  25. * <p>
  26. * <code>Format</code> defines the programming interface for formatting
  27. * locale-sensitive objects into <code>String</code>s (the
  28. * <code>format</code> method) and for parsing <code>String</code>s back
  29. * into objects (the <code>parseObject</code> method).
  30. *
  31. * <p>
  32. * Generally, a format's <code>parseObject</code> method must be able to parse
  33. * any string formatted by its <code>format</code> method. However, there may
  34. * be exceptional cases where this is not possible. For example, a
  35. * <code>format</code> method might create two adjacent integer numbers with
  36. * no separator in between, and in this case the <code>parseObject</code> could
  37. * not tell which digits belong to which number.
  38. *
  39. * <h4>Subclassing</h4>
  40. *
  41. * <p>
  42. * The Java 2 platform provides three specialized subclasses of <code>Format</code>--
  43. * <code>DateFormat</code>, <code>MessageFormat</code>, and
  44. * <code>NumberFormat</code>--for formatting dates, messages, and numbers,
  45. * respectively.
  46. * <p>
  47. * Concrete subclasses must implement three methods:
  48. * <ol>
  49. * <li> <code>format(Object obj, StringBuffer toAppendTo, FieldPosition pos)</code>
  50. * <li> <code>formatToCharacterIterator(Object obj)</code>
  51. * <li> <code>parseObject(String source, ParsePosition pos)</code>
  52. * </ol>
  53. * These general methods allow polymorphic parsing and formatting of objects
  54. * and are used, for example, by <code>MessageFormat</code>.
  55. * Subclasses often also provide additional <code>format</code> methods for
  56. * specific input types as well as <code>parse</code> methods for specific
  57. * result types. Any <code>parse</code> method that does not take a
  58. * <code>ParsePosition</code> argument should throw <code>ParseException</code>
  59. * when no text in the required format is at the beginning of the input text.
  60. *
  61. * <p>
  62. * Most subclasses will also implement the following factory methods:
  63. * <ol>
  64. * <li>
  65. * <code>getInstance</code> for getting a useful format object appropriate
  66. * for the current locale
  67. * <li>
  68. * <code>getInstance(Locale)</code> for getting a useful format
  69. * object appropriate for the specified locale
  70. * </ol>
  71. * In addition, some subclasses may also implement other
  72. * <code>getXxxxInstance</code> methods for more specialized control. For
  73. * example, the <code>NumberFormat</code> class provides
  74. * <code>getPercentInstance</code> and <code>getCurrencyInstance</code>
  75. * methods for getting specialized number formatters.
  76. *
  77. * <p>
  78. * Subclasses of <code>Format</code> that allow programmers to create objects
  79. * for locales (with <code>getInstance(Locale)</code> for example)
  80. * must also implement the following class method:
  81. * <blockquote>
  82. * <pre>
  83. * public static Locale[] getAvailableLocales()
  84. * </pre>
  85. * </blockquote>
  86. *
  87. * <p>
  88. * And finally subclasses may define a set of constants to identify the various
  89. * fields in the formatted output. These constants are used to create a FieldPosition
  90. * object which identifies what information is contained in the field and its
  91. * position in the formatted result. These constants should be named
  92. * <code><em>item</em>_FIELD</code> where <code><em>item</em></code> identifies
  93. * the field. For examples of these constants, see <code>ERA_FIELD</code> and its
  94. * friends in {@link DateFormat}.
  95. *
  96. * <h4><a name="synchronization">Synchronization</a></h4>
  97. *
  98. * <p>
  99. * Formats are generally not synchronized.
  100. * It is recommended to create separate format instances for each thread.
  101. * If multiple threads access a format concurrently, it must be synchronized
  102. * externally.
  103. *
  104. * @see java.text.ParsePosition
  105. * @see java.text.FieldPosition
  106. * @see java.text.NumberFormat
  107. * @see java.text.DateFormat
  108. * @see java.text.MessageFormat
  109. * @version 1.34, 12/19/03
  110. * @author Mark Davis
  111. */
  112. public abstract class Format implements Serializable, Cloneable {
  113. private static final long serialVersionUID = -299282585814624189L;
  114. /**
  115. * Formats an object to produce a string. This is equivalent to
  116. * <blockquote>
  117. * {@link #format(Object, StringBuffer, FieldPosition) format}<code>(obj,
  118. * new StringBuffer(), new FieldPosition(0)).toString();</code>
  119. * </blockquote>
  120. *
  121. * @param obj The object to format
  122. * @return Formatted string.
  123. * @exception IllegalArgumentException if the Format cannot format the given
  124. * object
  125. */
  126. public final String format (Object obj) {
  127. return format(obj, new StringBuffer(), new FieldPosition(0)).toString();
  128. }
  129. /**
  130. * Formats an object and appends the resulting text to a given string
  131. * buffer.
  132. * If the <code>pos</code> argument identifies a field used by the format,
  133. * then its indices are set to the beginning and end of the first such
  134. * field encountered.
  135. *
  136. * @param obj The object to format
  137. * @param toAppendTo where the text is to be appended
  138. * @param pos A <code>FieldPosition</code> identifying a field
  139. * in the formatted text
  140. * @return the string buffer passed in as <code>toAppendTo</code>,
  141. * with formatted text appended
  142. * @exception NullPointerException if <code>toAppendTo</code> or
  143. * <code>pos</code> is null
  144. * @exception IllegalArgumentException if the Format cannot format the given
  145. * object
  146. */
  147. public abstract StringBuffer format(Object obj,
  148. StringBuffer toAppendTo,
  149. FieldPosition pos);
  150. /**
  151. * Formats an Object producing an <code>AttributedCharacterIterator</code>.
  152. * You can use the returned <code>AttributedCharacterIterator</code>
  153. * to build the resulting String, as well as to determine information
  154. * about the resulting String.
  155. * <p>
  156. * Each attribute key of the AttributedCharacterIterator will be of type
  157. * <code>Field</code>. It is up to each <code>Format</code> implementation
  158. * to define what the legal values are for each attribute in the
  159. * <code>AttributedCharacterIterator</code>, but typically the attribute
  160. * key is also used as the attribute value.
  161. * <p>The default implementation creates an
  162. * <code>AttributedCharacterIterator</code> with no attributes. Subclasses
  163. * that support fields should override this and create an
  164. * <code>AttributedCharacterIterator</code> with meaningful attributes.
  165. *
  166. * @exception NullPointerException if obj is null.
  167. * @exception IllegalArgumentException when the Format cannot format the
  168. * given object.
  169. * @param obj The object to format
  170. * @return AttributedCharacterIterator describing the formatted value.
  171. * @since 1.4
  172. */
  173. public AttributedCharacterIterator formatToCharacterIterator(Object obj) {
  174. return createAttributedCharacterIterator(format(obj));
  175. }
  176. /**
  177. * Parses text from a string to produce an object.
  178. * <p>
  179. * The method attempts to parse text starting at the index given by
  180. * <code>pos</code>.
  181. * If parsing succeeds, then the index of <code>pos</code> is updated
  182. * to the index after the last character used (parsing does not necessarily
  183. * use all characters up to the end of the string), and the parsed
  184. * object is returned. The updated <code>pos</code> can be used to
  185. * indicate the starting point for the next call to this method.
  186. * If an error occurs, then the index of <code>pos</code> is not
  187. * changed, the error index of <code>pos</code> is set to the index of
  188. * the character where the error occurred, and null is returned.
  189. *
  190. * @param source A <code>String</code>, part of which should be parsed.
  191. * @param pos A <code>ParsePosition</code> object with index and error
  192. * index information as described above.
  193. * @return An <code>Object</code> parsed from the string. In case of
  194. * error, returns null.
  195. * @exception NullPointerException if <code>pos</code> is null.
  196. */
  197. public abstract Object parseObject (String source, ParsePosition pos);
  198. /**
  199. * Parses text from the beginning of the given string to produce an object.
  200. * The method may not use the entire text of the given string.
  201. *
  202. * @param source A <code>String</code> whose beginning should be parsed.
  203. * @return An <code>Object</code> parsed from the string.
  204. * @exception ParseException if the beginning of the specified string
  205. * cannot be parsed.
  206. */
  207. public Object parseObject(String source) throws ParseException {
  208. ParsePosition pos = new ParsePosition(0);
  209. Object result = parseObject(source, pos);
  210. if (pos.index == 0) {
  211. throw new ParseException("Format.parseObject(String) failed",
  212. pos.errorIndex);
  213. }
  214. return result;
  215. }
  216. /**
  217. * Creates and returns a copy of this object.
  218. *
  219. * @return a clone of this instance.
  220. */
  221. public Object clone() {
  222. try {
  223. return super.clone();
  224. } catch (CloneNotSupportedException e) {
  225. // will never happen
  226. return null;
  227. }
  228. }
  229. //
  230. // Convenience methods for creating AttributedCharacterIterators from
  231. // different parameters.
  232. //
  233. /**
  234. * Creates an <code>AttributedCharacterIterator</code> for the String
  235. * <code>s</code>.
  236. *
  237. * @param s String to create AttributedCharacterIterator from
  238. * @return AttributedCharacterIterator wrapping s
  239. */
  240. AttributedCharacterIterator createAttributedCharacterIterator(String s) {
  241. AttributedString as = new AttributedString(s);
  242. return as.getIterator();
  243. }
  244. /**
  245. * Creates an <code>AttributedCharacterIterator</code> containg the
  246. * concatenated contents of the passed in
  247. * <code>AttributedCharacterIterator</code>s.
  248. *
  249. * @param iterators AttributedCharacterIterators used to create resulting
  250. * AttributedCharacterIterators
  251. * @return AttributedCharacterIterator wrapping passed in
  252. * AttributedCharacterIterators
  253. */
  254. AttributedCharacterIterator createAttributedCharacterIterator(
  255. AttributedCharacterIterator[] iterators) {
  256. AttributedString as = new AttributedString(iterators);
  257. return as.getIterator();
  258. }
  259. /**
  260. * Returns an AttributedCharacterIterator with the String
  261. * <code>string</code> and additional key/value pair <code>key</code>,
  262. * <code>value</code>.
  263. *
  264. * @param string String to create AttributedCharacterIterator from
  265. * @param key Key for AttributedCharacterIterator
  266. * @param value Value associated with key in AttributedCharacterIterator
  267. * @return AttributedCharacterIterator wrapping args
  268. */
  269. AttributedCharacterIterator createAttributedCharacterIterator(
  270. String string, AttributedCharacterIterator.Attribute key,
  271. Object value) {
  272. AttributedString as = new AttributedString(string);
  273. as.addAttribute(key, value);
  274. return as.getIterator();
  275. }
  276. /**
  277. * Creates an AttributedCharacterIterator with the contents of
  278. * <code>iterator</code> and the additional attribute <code>key</code>
  279. * <code>value</code>.
  280. *
  281. * @param iterator Initial AttributedCharacterIterator to add arg to
  282. * @param key Key for AttributedCharacterIterator
  283. * @param value Value associated with key in AttributedCharacterIterator
  284. * @return AttributedCharacterIterator wrapping args
  285. */
  286. AttributedCharacterIterator createAttributedCharacterIterator(
  287. AttributedCharacterIterator iterator,
  288. AttributedCharacterIterator.Attribute key, Object value) {
  289. AttributedString as = new AttributedString(iterator);
  290. as.addAttribute(key, value);
  291. return as.getIterator();
  292. }
  293. /**
  294. * Defines constants that are used as attribute keys in the
  295. * <code>AttributedCharacterIterator</code> returned
  296. * from <code>Format.formatToCharacterIterator</code> and as
  297. * field identifiers in <code>FieldPosition</code>.
  298. *
  299. * @since 1.4
  300. */
  301. public static class Field extends AttributedCharacterIterator.Attribute {
  302. // Proclaim serial compatibility with 1.4 FCS
  303. private static final long serialVersionUID = 276966692217360283L;
  304. /**
  305. * Creates a Field with the specified name.
  306. *
  307. * @param name Name of the attribute
  308. */
  309. protected Field(String name) {
  310. super(name);
  311. }
  312. }
  313. /**
  314. * FieldDelegate is notified by the various <code>Format</code>
  315. * implementations as they are formatting the Objects. This allows for
  316. * storage of the individual sections of the formatted String for
  317. * later use, such as in a <code>FieldPosition</code> or for an
  318. * <code>AttributedCharacterIterator</code>.
  319. * <p>
  320. * Delegates should NOT assume that the <code>Format</code> will notify
  321. * the delegate of fields in any particular order.
  322. *
  323. * @see FieldPosition.Delegate
  324. * @see CharacterIteratorFieldDelegate
  325. */
  326. interface FieldDelegate {
  327. /**
  328. * Notified when a particular region of the String is formatted. This
  329. * method will be invoked if there is no corresponding integer field id
  330. * matching <code>attr</code>.
  331. *
  332. * @param attr Identifies the field matched
  333. * @param value Value associated with the field
  334. * @param start Beginning location of the field, will be >= 0
  335. * @param end End of the field, will be >= start and <= buffer.length()
  336. * @param buffer Contains current formatted value, receiver should
  337. * NOT modify it.
  338. */
  339. public void formatted(Format.Field attr, Object value, int start,
  340. int end, StringBuffer buffer);
  341. /**
  342. * Notified when a particular region of the String is formatted.
  343. *
  344. * @param fieldID Identifies the field by integer
  345. * @param attr Identifies the field matched
  346. * @param value Value associated with the field
  347. * @param start Beginning location of the field, will be >= 0
  348. * @param end End of the field, will be >= start and <= buffer.length()
  349. * @param buffer Contains current formatted value, receiver should
  350. * NOT modify it.
  351. */
  352. public void formatted(int fieldID, Format.Field attr, Object value,
  353. int start, int end, StringBuffer buffer);
  354. }
  355. }