001 /*
002 * Copyright 1996-2005 Sun Microsystems, Inc. All Rights Reserved.
003 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004 *
005 * This code is free software; you can redistribute it and/or modify it
006 * under the terms of the GNU General Public License version 2 only, as
007 * published by the Free Software Foundation. Sun designates this
008 * particular file as subject to the "Classpath" exception as provided
009 * by Sun in the LICENSE file that accompanied this code.
010 *
011 * This code is distributed in the hope that it will be useful, but WITHOUT
012 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014 * version 2 for more details (a copy is included in the LICENSE file that
015 * accompanied this code).
016 *
017 * You should have received a copy of the GNU General Public License version
018 * 2 along with this work; if not, write to the Free Software Foundation,
019 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020 *
021 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022 * CA 95054 USA or visit www.sun.com if you need additional information or
023 * have any questions.
024 */
025
026 /*
027 * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
028 * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
029 *
030 * The original version of this source code and documentation is copyrighted
031 * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
032 * materials are provided under terms of a License Agreement between Taligent
033 * and Sun. This technology is protected by multiple US and International
034 * patents. This notice and attribution to Taligent may not be removed.
035 * Taligent is a registered trademark of Taligent, Inc.
036 *
037 */
038
039 package java.text;
040
041 import java.io.Serializable;
042
043 /**
044 * <code>Format</code> is an abstract base class for formatting locale-sensitive
045 * information such as dates, messages, and numbers.
046 *
047 * <p>
048 * <code>Format</code> defines the programming interface for formatting
049 * locale-sensitive objects into <code>String</code>s (the
050 * <code>format</code> method) and for parsing <code>String</code>s back
051 * into objects (the <code>parseObject</code> method).
052 *
053 * <p>
054 * Generally, a format's <code>parseObject</code> method must be able to parse
055 * any string formatted by its <code>format</code> method. However, there may
056 * be exceptional cases where this is not possible. For example, a
057 * <code>format</code> method might create two adjacent integer numbers with
058 * no separator in between, and in this case the <code>parseObject</code> could
059 * not tell which digits belong to which number.
060 *
061 * <h4>Subclassing</h4>
062 *
063 * <p>
064 * The Java Platform provides three specialized subclasses of <code>Format</code>--
065 * <code>DateFormat</code>, <code>MessageFormat</code>, and
066 * <code>NumberFormat</code>--for formatting dates, messages, and numbers,
067 * respectively.
068 * <p>
069 * Concrete subclasses must implement three methods:
070 * <ol>
071 * <li> <code>format(Object obj, StringBuffer toAppendTo, FieldPosition pos)</code>
072 * <li> <code>formatToCharacterIterator(Object obj)</code>
073 * <li> <code>parseObject(String source, ParsePosition pos)</code>
074 * </ol>
075 * These general methods allow polymorphic parsing and formatting of objects
076 * and are used, for example, by <code>MessageFormat</code>.
077 * Subclasses often also provide additional <code>format</code> methods for
078 * specific input types as well as <code>parse</code> methods for specific
079 * result types. Any <code>parse</code> method that does not take a
080 * <code>ParsePosition</code> argument should throw <code>ParseException</code>
081 * when no text in the required format is at the beginning of the input text.
082 *
083 * <p>
084 * Most subclasses will also implement the following factory methods:
085 * <ol>
086 * <li>
087 * <code>getInstance</code> for getting a useful format object appropriate
088 * for the current locale
089 * <li>
090 * <code>getInstance(Locale)</code> for getting a useful format
091 * object appropriate for the specified locale
092 * </ol>
093 * In addition, some subclasses may also implement other
094 * <code>getXxxxInstance</code> methods for more specialized control. For
095 * example, the <code>NumberFormat</code> class provides
096 * <code>getPercentInstance</code> and <code>getCurrencyInstance</code>
097 * methods for getting specialized number formatters.
098 *
099 * <p>
100 * Subclasses of <code>Format</code> that allow programmers to create objects
101 * for locales (with <code>getInstance(Locale)</code> for example)
102 * must also implement the following class method:
103 * <blockquote>
104 * <pre>
105 * public static Locale[] getAvailableLocales()
106 * </pre>
107 * </blockquote>
108 *
109 * <p>
110 * And finally subclasses may define a set of constants to identify the various
111 * fields in the formatted output. These constants are used to create a FieldPosition
112 * object which identifies what information is contained in the field and its
113 * position in the formatted result. These constants should be named
114 * <code><em>item</em>_FIELD</code> where <code><em>item</em></code> identifies
115 * the field. For examples of these constants, see <code>ERA_FIELD</code> and its
116 * friends in {@link DateFormat}.
117 *
118 * <h4><a name="synchronization">Synchronization</a></h4>
119 *
120 * <p>
121 * Formats are generally not synchronized.
122 * It is recommended to create separate format instances for each thread.
123 * If multiple threads access a format concurrently, it must be synchronized
124 * externally.
125 *
126 * @see java.text.ParsePosition
127 * @see java.text.FieldPosition
128 * @see java.text.NumberFormat
129 * @see java.text.DateFormat
130 * @see java.text.MessageFormat
131 * @version 1.43, 05/05/07
132 * @author Mark Davis
133 */
134 public abstract class Format implements Serializable, Cloneable {
135
136 private static final long serialVersionUID = -299282585814624189L;
137
138 /**
139 * Sole constructor. (For invocation by subclass constructors, typically
140 * implicit.)
141 */
142 protected Format() {
143 }
144
145 /**
146 * Formats an object to produce a string. This is equivalent to
147 * <blockquote>
148 * {@link #format(Object, StringBuffer, FieldPosition) format}<code>(obj,
149 * new StringBuffer(), new FieldPosition(0)).toString();</code>
150 * </blockquote>
151 *
152 * @param obj The object to format
153 * @return Formatted string.
154 * @exception IllegalArgumentException if the Format cannot format the given
155 * object
156 */
157 public final String format(Object obj) {
158 return format(obj, new StringBuffer(), new FieldPosition(0))
159 .toString();
160 }
161
162 /**
163 * Formats an object and appends the resulting text to a given string
164 * buffer.
165 * If the <code>pos</code> argument identifies a field used by the format,
166 * then its indices are set to the beginning and end of the first such
167 * field encountered.
168 *
169 * @param obj The object to format
170 * @param toAppendTo where the text is to be appended
171 * @param pos A <code>FieldPosition</code> identifying a field
172 * in the formatted text
173 * @return the string buffer passed in as <code>toAppendTo</code>,
174 * with formatted text appended
175 * @exception NullPointerException if <code>toAppendTo</code> or
176 * <code>pos</code> is null
177 * @exception IllegalArgumentException if the Format cannot format the given
178 * object
179 */
180 public abstract StringBuffer format(Object obj,
181 StringBuffer toAppendTo, FieldPosition pos);
182
183 /**
184 * Formats an Object producing an <code>AttributedCharacterIterator</code>.
185 * You can use the returned <code>AttributedCharacterIterator</code>
186 * to build the resulting String, as well as to determine information
187 * about the resulting String.
188 * <p>
189 * Each attribute key of the AttributedCharacterIterator will be of type
190 * <code>Field</code>. It is up to each <code>Format</code> implementation
191 * to define what the legal values are for each attribute in the
192 * <code>AttributedCharacterIterator</code>, but typically the attribute
193 * key is also used as the attribute value.
194 * <p>The default implementation creates an
195 * <code>AttributedCharacterIterator</code> with no attributes. Subclasses
196 * that support fields should override this and create an
197 * <code>AttributedCharacterIterator</code> with meaningful attributes.
198 *
199 * @exception NullPointerException if obj is null.
200 * @exception IllegalArgumentException when the Format cannot format the
201 * given object.
202 * @param obj The object to format
203 * @return AttributedCharacterIterator describing the formatted value.
204 * @since 1.4
205 */
206 public AttributedCharacterIterator formatToCharacterIterator(
207 Object obj) {
208 return createAttributedCharacterIterator(format(obj));
209 }
210
211 /**
212 * Parses text from a string to produce an object.
213 * <p>
214 * The method attempts to parse text starting at the index given by
215 * <code>pos</code>.
216 * If parsing succeeds, then the index of <code>pos</code> is updated
217 * to the index after the last character used (parsing does not necessarily
218 * use all characters up to the end of the string), and the parsed
219 * object is returned. The updated <code>pos</code> can be used to
220 * indicate the starting point for the next call to this method.
221 * If an error occurs, then the index of <code>pos</code> is not
222 * changed, the error index of <code>pos</code> is set to the index of
223 * the character where the error occurred, and null is returned.
224 *
225 * @param source A <code>String</code>, part of which should be parsed.
226 * @param pos A <code>ParsePosition</code> object with index and error
227 * index information as described above.
228 * @return An <code>Object</code> parsed from the string. In case of
229 * error, returns null.
230 * @exception NullPointerException if <code>pos</code> is null.
231 */
232 public abstract Object parseObject(String source, ParsePosition pos);
233
234 /**
235 * Parses text from the beginning of the given string to produce an object.
236 * The method may not use the entire text of the given string.
237 *
238 * @param source A <code>String</code> whose beginning should be parsed.
239 * @return An <code>Object</code> parsed from the string.
240 * @exception ParseException if the beginning of the specified string
241 * cannot be parsed.
242 */
243 public Object parseObject(String source) throws ParseException {
244 ParsePosition pos = new ParsePosition(0);
245 Object result = parseObject(source, pos);
246 if (pos.index == 0) {
247 throw new ParseException(
248 "Format.parseObject(String) failed", pos.errorIndex);
249 }
250 return result;
251 }
252
253 /**
254 * Creates and returns a copy of this object.
255 *
256 * @return a clone of this instance.
257 */
258 public Object clone() {
259 try {
260 return super .clone();
261 } catch (CloneNotSupportedException e) {
262 // will never happen
263 return null;
264 }
265 }
266
267 //
268 // Convenience methods for creating AttributedCharacterIterators from
269 // different parameters.
270 //
271
272 /**
273 * Creates an <code>AttributedCharacterIterator</code> for the String
274 * <code>s</code>.
275 *
276 * @param s String to create AttributedCharacterIterator from
277 * @return AttributedCharacterIterator wrapping s
278 */
279 AttributedCharacterIterator createAttributedCharacterIterator(
280 String s) {
281 AttributedString as = new AttributedString(s);
282
283 return as.getIterator();
284 }
285
286 /**
287 * Creates an <code>AttributedCharacterIterator</code> containg the
288 * concatenated contents of the passed in
289 * <code>AttributedCharacterIterator</code>s.
290 *
291 * @param iterators AttributedCharacterIterators used to create resulting
292 * AttributedCharacterIterators
293 * @return AttributedCharacterIterator wrapping passed in
294 * AttributedCharacterIterators
295 */
296 AttributedCharacterIterator createAttributedCharacterIterator(
297 AttributedCharacterIterator[] iterators) {
298 AttributedString as = new AttributedString(iterators);
299
300 return as.getIterator();
301 }
302
303 /**
304 * Returns an AttributedCharacterIterator with the String
305 * <code>string</code> and additional key/value pair <code>key</code>,
306 * <code>value</code>.
307 *
308 * @param string String to create AttributedCharacterIterator from
309 * @param key Key for AttributedCharacterIterator
310 * @param value Value associated with key in AttributedCharacterIterator
311 * @return AttributedCharacterIterator wrapping args
312 */
313 AttributedCharacterIterator createAttributedCharacterIterator(
314 String string, AttributedCharacterIterator.Attribute key,
315 Object value) {
316 AttributedString as = new AttributedString(string);
317
318 as.addAttribute(key, value);
319 return as.getIterator();
320 }
321
322 /**
323 * Creates an AttributedCharacterIterator with the contents of
324 * <code>iterator</code> and the additional attribute <code>key</code>
325 * <code>value</code>.
326 *
327 * @param iterator Initial AttributedCharacterIterator to add arg to
328 * @param key Key for AttributedCharacterIterator
329 * @param value Value associated with key in AttributedCharacterIterator
330 * @return AttributedCharacterIterator wrapping args
331 */
332 AttributedCharacterIterator createAttributedCharacterIterator(
333 AttributedCharacterIterator iterator,
334 AttributedCharacterIterator.Attribute key, Object value) {
335 AttributedString as = new AttributedString(iterator);
336
337 as.addAttribute(key, value);
338 return as.getIterator();
339 }
340
341 /**
342 * Defines constants that are used as attribute keys in the
343 * <code>AttributedCharacterIterator</code> returned
344 * from <code>Format.formatToCharacterIterator</code> and as
345 * field identifiers in <code>FieldPosition</code>.
346 *
347 * @since 1.4
348 */
349 public static class Field extends
350 AttributedCharacterIterator.Attribute {
351
352 // Proclaim serial compatibility with 1.4 FCS
353 private static final long serialVersionUID = 276966692217360283L;
354
355 /**
356 * Creates a Field with the specified name.
357 *
358 * @param name Name of the attribute
359 */
360 protected Field(String name) {
361 super (name);
362 }
363 }
364
365 /**
366 * FieldDelegate is notified by the various <code>Format</code>
367 * implementations as they are formatting the Objects. This allows for
368 * storage of the individual sections of the formatted String for
369 * later use, such as in a <code>FieldPosition</code> or for an
370 * <code>AttributedCharacterIterator</code>.
371 * <p>
372 * Delegates should NOT assume that the <code>Format</code> will notify
373 * the delegate of fields in any particular order.
374 *
375 * @see FieldPosition.Delegate
376 * @see CharacterIteratorFieldDelegate
377 */
378 interface FieldDelegate {
379 /**
380 * Notified when a particular region of the String is formatted. This
381 * method will be invoked if there is no corresponding integer field id
382 * matching <code>attr</code>.
383 *
384 * @param attr Identifies the field matched
385 * @param value Value associated with the field
386 * @param start Beginning location of the field, will be >= 0
387 * @param end End of the field, will be >= start and <= buffer.length()
388 * @param buffer Contains current formatted value, receiver should
389 * NOT modify it.
390 */
391 public void formatted(Format.Field attr, Object value,
392 int start, int end, StringBuffer buffer);
393
394 /**
395 * Notified when a particular region of the String is formatted.
396 *
397 * @param fieldID Identifies the field by integer
398 * @param attr Identifies the field matched
399 * @param value Value associated with the field
400 * @param start Beginning location of the field, will be >= 0
401 * @param end End of the field, will be >= start and <= buffer.length()
402 * @param buffer Contains current formatted value, receiver should
403 * NOT modify it.
404 */
405 public void formatted(int fieldID, Format.Field attr,
406 Object value, int start, int end, StringBuffer buffer);
407 }
408 }
|