KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > text > Format


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 /*
9  * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
10  * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
11  *
12  * The original version of this source code and documentation is copyrighted
13  * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
14  * materials are provided under terms of a License Agreement between Taligent
15  * and Sun. This technology is protected by multiple US and International
16  * patents. This notice and attribution to Taligent may not be removed.
17  * Taligent is a registered trademark of Taligent, Inc.
18  *
19  */

20
21 package java.text;
22
23 import java.io.Serializable JavaDoc;
24
25 /**
26  * <code>Format</code> is an abstract base class for formatting locale-sensitive
27  * information such as dates, messages, and numbers.
28  *
29  * <p>
30  * <code>Format</code> defines the programming interface for formatting
31  * locale-sensitive objects into <code>String</code>s (the
32  * <code>format</code> method) and for parsing <code>String</code>s back
33  * into objects (the <code>parseObject</code> method).
34  *
35  * <p>
36  * Generally, a format's <code>parseObject</code> method must be able to parse
37  * any string formatted by its <code>format</code> method. However, there may
38  * be exceptional cases where this is not possible. For example, a
39  * <code>format</code> method might create two adjacent integer numbers with
40  * no separator in between, and in this case the <code>parseObject</code> could
41  * not tell which digits belong to which number.
42  *
43  * <h4>Subclassing</h4>
44  *
45  * <p>
46  * The Java 2 platform provides three specialized subclasses of <code>Format</code>--
47  * <code>DateFormat</code>, <code>MessageFormat</code>, and
48  * <code>NumberFormat</code>--for formatting dates, messages, and numbers,
49  * respectively.
50  * <p>
51  * Concrete subclasses must implement three methods:
52  * <ol>
53  * <li> <code>format(Object obj, StringBuffer toAppendTo, FieldPosition pos)</code>
54  * <li> <code>formatToCharacterIterator(Object obj)</code>
55  * <li> <code>parseObject(String source, ParsePosition pos)</code>
56  * </ol>
57  * These general methods allow polymorphic parsing and formatting of objects
58  * and are used, for example, by <code>MessageFormat</code>.
59  * Subclasses often also provide additional <code>format</code> methods for
60  * specific input types as well as <code>parse</code> methods for specific
61  * result types. Any <code>parse</code> method that does not take a
62  * <code>ParsePosition</code> argument should throw <code>ParseException</code>
63  * when no text in the required format is at the beginning of the input text.
64  *
65  * <p>
66  * Most subclasses will also implement the following factory methods:
67  * <ol>
68  * <li>
69  * <code>getInstance</code> for getting a useful format object appropriate
70  * for the current locale
71  * <li>
72  * <code>getInstance(Locale)</code> for getting a useful format
73  * object appropriate for the specified locale
74  * </ol>
75  * In addition, some subclasses may also implement other
76  * <code>getXxxxInstance</code> methods for more specialized control. For
77  * example, the <code>NumberFormat</code> class provides
78  * <code>getPercentInstance</code> and <code>getCurrencyInstance</code>
79  * methods for getting specialized number formatters.
80  *
81  * <p>
82  * Subclasses of <code>Format</code> that allow programmers to create objects
83  * for locales (with <code>getInstance(Locale)</code> for example)
84  * must also implement the following class method:
85  * <blockquote>
86  * <pre>
87  * public static Locale[] getAvailableLocales()
88  * </pre>
89  * </blockquote>
90  *
91  * <p>
92  * And finally subclasses may define a set of constants to identify the various
93  * fields in the formatted output. These constants are used to create a FieldPosition
94  * object which identifies what information is contained in the field and its
95  * position in the formatted result. These constants should be named
96  * <code><em>item</em>_FIELD</code> where <code><em>item</em></code> identifies
97  * the field. For examples of these constants, see <code>ERA_FIELD</code> and its
98  * friends in {@link DateFormat}.
99  *
100  * <h4><a name="synchronization">Synchronization</a></h4>
101  *
102  * <p>
103  * Formats are generally not synchronized.
104  * It is recommended to create separate format instances for each thread.
105  * If multiple threads access a format concurrently, it must be synchronized
106  * externally.
107  *
108  * @see java.text.ParsePosition
109  * @see java.text.FieldPosition
110  * @see java.text.NumberFormat
111  * @see java.text.DateFormat
112  * @see java.text.MessageFormat
113  * @version 1.34, 12/19/03
114  * @author Mark Davis
115  */

116 public abstract class Format implements Serializable JavaDoc, Cloneable JavaDoc {
117
118     private static final long serialVersionUID = -299282585814624189L;
119
120     /**
121      * Formats an object to produce a string. This is equivalent to
122      * <blockquote>
123      * {@link #format(Object, StringBuffer, FieldPosition) format}<code>(obj,
124      * new StringBuffer(), new FieldPosition(0)).toString();</code>
125      * </blockquote>
126      *
127      * @param obj The object to format
128      * @return Formatted string.
129      * @exception IllegalArgumentException if the Format cannot format the given
130      * object
131      */

132     public final String JavaDoc format (Object JavaDoc obj) {
133         return format(obj, new StringBuffer JavaDoc(), new FieldPosition JavaDoc(0)).toString();
134     }
135
136     /**
137      * Formats an object and appends the resulting text to a given string
138      * buffer.
139      * If the <code>pos</code> argument identifies a field used by the format,
140      * then its indices are set to the beginning and end of the first such
141      * field encountered.
142      *
143      * @param obj The object to format
144      * @param toAppendTo where the text is to be appended
145      * @param pos A <code>FieldPosition</code> identifying a field
146      * in the formatted text
147      * @return the string buffer passed in as <code>toAppendTo</code>,
148      * with formatted text appended
149      * @exception NullPointerException if <code>toAppendTo</code> or
150      * <code>pos</code> is null
151      * @exception IllegalArgumentException if the Format cannot format the given
152      * object
153      */

154     public abstract StringBuffer JavaDoc format(Object JavaDoc obj,
155                     StringBuffer JavaDoc toAppendTo,
156                     FieldPosition JavaDoc pos);
157
158     /**
159      * Formats an Object producing an <code>AttributedCharacterIterator</code>.
160      * You can use the returned <code>AttributedCharacterIterator</code>
161      * to build the resulting String, as well as to determine information
162      * about the resulting String.
163      * <p>
164      * Each attribute key of the AttributedCharacterIterator will be of type
165      * <code>Field</code>. It is up to each <code>Format</code> implementation
166      * to define what the legal values are for each attribute in the
167      * <code>AttributedCharacterIterator</code>, but typically the attribute
168      * key is also used as the attribute value.
169      * <p>The default implementation creates an
170      * <code>AttributedCharacterIterator</code> with no attributes. Subclasses
171      * that support fields should override this and create an
172      * <code>AttributedCharacterIterator</code> with meaningful attributes.
173      *
174      * @exception NullPointerException if obj is null.
175      * @exception IllegalArgumentException when the Format cannot format the
176      * given object.
177      * @param obj The object to format
178      * @return AttributedCharacterIterator describing the formatted value.
179      * @since 1.4
180      */

181     public AttributedCharacterIterator JavaDoc formatToCharacterIterator(Object JavaDoc obj) {
182         return createAttributedCharacterIterator(format(obj));
183     }
184
185     /**
186      * Parses text from a string to produce an object.
187      * <p>
188      * The method attempts to parse text starting at the index given by
189      * <code>pos</code>.
190      * If parsing succeeds, then the index of <code>pos</code> is updated
191      * to the index after the last character used (parsing does not necessarily
192      * use all characters up to the end of the string), and the parsed
193      * object is returned. The updated <code>pos</code> can be used to
194      * indicate the starting point for the next call to this method.
195      * If an error occurs, then the index of <code>pos</code> is not
196      * changed, the error index of <code>pos</code> is set to the index of
197      * the character where the error occurred, and null is returned.
198      *
199      * @param source A <code>String</code>, part of which should be parsed.
200      * @param pos A <code>ParsePosition</code> object with index and error
201      * index information as described above.
202      * @return An <code>Object</code> parsed from the string. In case of
203      * error, returns null.
204      * @exception NullPointerException if <code>pos</code> is null.
205      */

206     public abstract Object JavaDoc parseObject (String JavaDoc source, ParsePosition JavaDoc pos);
207
208     /**
209      * Parses text from the beginning of the given string to produce an object.
210      * The method may not use the entire text of the given string.
211      *
212      * @param source A <code>String</code> whose beginning should be parsed.
213      * @return An <code>Object</code> parsed from the string.
214      * @exception ParseException if the beginning of the specified string
215      * cannot be parsed.
216      */

217     public Object JavaDoc parseObject(String JavaDoc source) throws ParseException JavaDoc {
218         ParsePosition JavaDoc pos = new ParsePosition JavaDoc(0);
219         Object JavaDoc result = parseObject(source, pos);
220         if (pos.index == 0) {
221             throw new ParseException JavaDoc("Format.parseObject(String) failed",
222                 pos.errorIndex);
223         }
224         return result;
225     }
226
227     /**
228      * Creates and returns a copy of this object.
229      *
230      * @return a clone of this instance.
231      */

232     public Object JavaDoc clone() {
233         try {
234             return super.clone();
235         } catch (CloneNotSupportedException JavaDoc e) {
236             // will never happen
237
return null;
238         }
239     }
240
241     //
242
// Convenience methods for creating AttributedCharacterIterators from
243
// different parameters.
244
//
245

246     /**
247      * Creates an <code>AttributedCharacterIterator</code> for the String
248      * <code>s</code>.
249      *
250      * @param s String to create AttributedCharacterIterator from
251      * @return AttributedCharacterIterator wrapping s
252      */

253     AttributedCharacterIterator JavaDoc createAttributedCharacterIterator(String JavaDoc s) {
254     AttributedString JavaDoc as = new AttributedString JavaDoc(s);
255
256     return as.getIterator();
257     }
258
259     /**
260      * Creates an <code>AttributedCharacterIterator</code> containg the
261      * concatenated contents of the passed in
262      * <code>AttributedCharacterIterator</code>s.
263      *
264      * @param iterators AttributedCharacterIterators used to create resulting
265      * AttributedCharacterIterators
266      * @return AttributedCharacterIterator wrapping passed in
267      * AttributedCharacterIterators
268      */

269     AttributedCharacterIterator JavaDoc createAttributedCharacterIterator(
270                        AttributedCharacterIterator JavaDoc[] iterators) {
271         AttributedString JavaDoc as = new AttributedString JavaDoc(iterators);
272
273         return as.getIterator();
274     }
275
276     /**
277      * Returns an AttributedCharacterIterator with the String
278      * <code>string</code> and additional key/value pair <code>key</code>,
279      * <code>value</code>.
280      *
281      * @param string String to create AttributedCharacterIterator from
282      * @param key Key for AttributedCharacterIterator
283      * @param value Value associated with key in AttributedCharacterIterator
284      * @return AttributedCharacterIterator wrapping args
285      */

286     AttributedCharacterIterator JavaDoc createAttributedCharacterIterator(
287                       String JavaDoc string, AttributedCharacterIterator.Attribute JavaDoc key,
288                       Object JavaDoc value) {
289         AttributedString JavaDoc as = new AttributedString JavaDoc(string);
290
291         as.addAttribute(key, value);
292         return as.getIterator();
293     }
294
295     /**
296      * Creates an AttributedCharacterIterator with the contents of
297      * <code>iterator</code> and the additional attribute <code>key</code>
298      * <code>value</code>.
299      *
300      * @param iterator Initial AttributedCharacterIterator to add arg to
301      * @param key Key for AttributedCharacterIterator
302      * @param value Value associated with key in AttributedCharacterIterator
303      * @return AttributedCharacterIterator wrapping args
304      */

305     AttributedCharacterIterator JavaDoc createAttributedCharacterIterator(
306           AttributedCharacterIterator JavaDoc iterator,
307               AttributedCharacterIterator.Attribute JavaDoc key, Object JavaDoc value) {
308     AttributedString JavaDoc as = new AttributedString JavaDoc(iterator);
309
310     as.addAttribute(key, value);
311     return as.getIterator();
312     }
313
314
315     /**
316      * Defines constants that are used as attribute keys in the
317      * <code>AttributedCharacterIterator</code> returned
318      * from <code>Format.formatToCharacterIterator</code> and as
319      * field identifiers in <code>FieldPosition</code>.
320      *
321      * @since 1.4
322      */

323     public static class Field extends AttributedCharacterIterator.Attribute JavaDoc {
324
325         // Proclaim serial compatibility with 1.4 FCS
326
private static final long serialVersionUID = 276966692217360283L;
327
328         /**
329          * Creates a Field with the specified name.
330          *
331          * @param name Name of the attribute
332          */

333         protected Field(String JavaDoc name) {
334             super(name);
335         }
336     }
337
338
339     /**
340      * FieldDelegate is notified by the various <code>Format</code>
341      * implementations as they are formatting the Objects. This allows for
342      * storage of the individual sections of the formatted String for
343      * later use, such as in a <code>FieldPosition</code> or for an
344      * <code>AttributedCharacterIterator</code>.
345      * <p>
346      * Delegates should NOT assume that the <code>Format</code> will notify
347      * the delegate of fields in any particular order.
348      *
349      * @see FieldPosition.Delegate
350      * @see CharacterIteratorFieldDelegate
351      */

352     interface FieldDelegate {
353         /**
354          * Notified when a particular region of the String is formatted. This
355          * method will be invoked if there is no corresponding integer field id
356          * matching <code>attr</code>.
357          *
358          * @param attr Identifies the field matched
359          * @param value Value associated with the field
360          * @param start Beginning location of the field, will be >= 0
361          * @param end End of the field, will be >= start and <= buffer.length()
362          * @param buffer Contains current formatted value, receiver should
363          * NOT modify it.
364          */

365         public void formatted(Format.Field JavaDoc attr, Object JavaDoc value, int start,
366                               int end, StringBuffer JavaDoc buffer);
367
368         /**
369          * Notified when a particular region of the String is formatted.
370          *
371          * @param fieldID Identifies the field by integer
372          * @param attr Identifies the field matched
373          * @param value Value associated with the field
374          * @param start Beginning location of the field, will be >= 0
375          * @param end End of the field, will be >= start and <= buffer.length()
376          * @param buffer Contains current formatted value, receiver should
377          * NOT modify it.
378          */

379         public void formatted(int fieldID, Format.Field JavaDoc attr, Object JavaDoc value,
380                               int start, int end, StringBuffer JavaDoc buffer);
381     }
382 }
383
Popular Tags