001: /*
002: *
003: * @(#)ChoiceFormat.java 1.34 06/10/10
004: *
005: * Portions Copyright 2000-2006 Sun Microsystems, Inc. All Rights
006: * Reserved. Use is subject to license terms.
007: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
008: *
009: * This program is free software; you can redistribute it and/or
010: * modify it under the terms of the GNU General Public License version
011: * 2 only, as published by the Free Software Foundation.
012: *
013: * This program is distributed in the hope that it will be useful, but
014: * WITHOUT ANY WARRANTY; without even the implied warranty of
015: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
016: * General Public License version 2 for more details (a copy is
017: * included at /legal/license.txt).
018: *
019: * You should have received a copy of the GNU General Public License
020: * version 2 along with this work; if not, write to the Free Software
021: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
022: * 02110-1301 USA
023: *
024: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
025: * Clara, CA 95054 or visit www.sun.com if you need additional
026: * information or have any questions.
027: */
028:
029: /*
030: * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
031: * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
032: *
033: * The original version of this source code and documentation is copyrighted
034: * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
035: * materials are provided under terms of a License Agreement between Taligent
036: * and Sun. This technology is protected by multiple US and International
037: * patents. This notice and attribution to Taligent may not be removed.
038: * Taligent is a registered trademark of Taligent, Inc.
039: *
040: */
041:
042: package java.text;
043:
044: import java.io.InvalidObjectException;
045: import java.io.IOException;
046: import java.io.ObjectInputStream;
047: import sun.text.Utility;
048:
049: /**
050: * A <code>ChoiceFormat</code> allows you to attach a format to a range of numbers.
051: * It is generally used in a <code>MessageFormat</code> for handling plurals.
052: * The choice is specified with an ascending list of doubles, where each item
053: * specifies a half-open interval up to the next item:
054: * <blockquote>
055: * <pre>
056: * X matches j if and only if limit[j] <= X < limit[j+1]
057: * </pre>
058: * </blockquote>
059: * If there is no match, then either the first or last index is used, depending
060: * on whether the number (X) is too low or too high. If the limit array is not
061: * in ascending order, the results of formatting will be incorrect. ChoiceFormat
062: * also accepts <code>\u221E</code> as equivalent to infinity(INF).
063: *
064: * <p>
065: * <strong>Note:</strong>
066: * <code>ChoiceFormat</code> differs from the other <code>Format</code>
067: * classes in that you create a <code>ChoiceFormat</code> object with a
068: * constructor (not with a <code>getInstance</code> style factory
069: * method). The factory methods aren't necessary because <code>ChoiceFormat</code>
070: * doesn't require any complex setup for a given locale. In fact,
071: * <code>ChoiceFormat</code> doesn't implement any locale specific behavior.
072: *
073: * <p>
074: * When creating a <code>ChoiceFormat</code>, you must specify an array of formats
075: * and an array of limits. The length of these arrays must be the same.
076: * For example,
077: * <ul>
078: * <li>
079: * <em>limits</em> = {1,2,3,4,5,6,7}<br>
080: * <em>formats</em> = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}
081: * <li>
082: * <em>limits</em> = {0, 1, ChoiceFormat.nextDouble(1)}<br>
083: * <em>formats</em> = {"no files", "one file", "many files"}<br>
084: * (<code>nextDouble</code> can be used to get the next higher double, to
085: * make the half-open interval.)
086: * </ul>
087: *
088: * <p>
089: * Here is a simple example that shows formatting and parsing:
090: * <blockquote>
091: * <pre>
092: * double[] limits = {1,2,3,4,5,6,7};
093: * String[] monthNames = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
094: * ChoiceFormat form = new ChoiceFormat(limits, monthNames);
095: * ParsePosition status = new ParsePosition(0);
096: * for (double i = 0.0; i <= 8.0; ++i) {
097: * status.setIndex(0);
098: * System.out.println(i + " -> " + form.format(i) + " -> "
099: * + form.parse(form.format(i),status));
100: * }
101: * </pre>
102: * </blockquote>
103: * Here is a more complex example, with a pattern format:
104: * <blockquote>
105: * <pre>
106: * double[] filelimits = {0,1,2};
107: * String[] filepart = {"are no files","is one file","are {2} files"};
108: * ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
109: * Format[] testFormats = {fileform, null, NumberFormat.getInstance()};
110: * MessageFormat pattform = new MessageFormat("There {0} on {1}");
111: * pattform.setFormats(testFormats);
112: * Object[] testArgs = {null, "ADisk", null};
113: * for (int i = 0; i < 4; ++i) {
114: * testArgs[0] = new Integer(i);
115: * testArgs[2] = testArgs[0];
116: * System.out.println(pattform.format(testArgs));
117: * }
118: * </pre>
119: * </blockquote>
120: * <p>
121: * Specifying a pattern for ChoiceFormat objects is fairly straightforward.
122: * For example:
123: * <blockquote>
124: * <pre>
125: * ChoiceFormat fmt = new ChoiceFormat(
126: * "-1#is negative| 0#is zero or fraction | 1#is one |1.0<is 1+ |2#is two |2<is more than 2.");
127: * System.out.println("Formatter Pattern : " + fmt.toPattern());
128: *
129: * System.out.println("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY));
130: * System.out.println("Format with -1.0 : " + fmt.format(-1.0));
131: * System.out.println("Format with 0 : " + fmt.format(0));
132: * System.out.println("Format with 0.9 : " + fmt.format(0.9));
133: * System.out.println("Format with 1.0 : " + fmt.format(1));
134: * System.out.println("Format with 1.5 : " + fmt.format(1.5));
135: * System.out.println("Format with 2 : " + fmt.format(2));
136: * System.out.println("Format with 2.1 : " + fmt.format(2.1));
137: * System.out.println("Format with NaN : " + fmt.format(Double.NaN));
138: * System.out.println("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY));
139: * </pre>
140: * </blockquote>
141: * And the output result would be like the following:
142: * <pre>
143: * <blockquote>
144: * Format with -INF : is negative
145: * Format with -1.0 : is negative
146: * Format with 0 : is zero or fraction
147: * Format with 0.9 : is zero or fraction
148: * Format with 1.0 : is one
149: * Format with 1.5 : is 1+
150: * Format with 2 : is two
151: * Format with 2.1 : is more than 2.
152: * Format with NaN : is negative
153: * Format with +INF : is more than 2.
154: * </pre>
155: * </blockquote>
156: *
157: * <h4><a name="synchronization">Synchronization</a></h4>
158: *
159: * <p>
160: * Choice formats are not synchronized.
161: * It is recommended to create separate format instances for each thread.
162: * If multiple threads access a format concurrently, it must be synchronized
163: * externally.
164: *
165: *
166: * @see DecimalFormat
167: * @see MessageFormat
168: * @version 1.34, 10/10/06
169: */
170: public class ChoiceFormat extends NumberFormat {
171:
172: /**
173: * Sets the pattern.
174: * @param newPattern See the class description.
175: */
176: public void applyPattern(String newPattern) {
177: StringBuffer[] segments = new StringBuffer[2];
178: for (int i = 0; i < segments.length; ++i) {
179: segments[i] = new StringBuffer();
180: }
181: double[] newChoiceLimits = new double[30];
182: String[] newChoiceFormats = new String[30];
183: int count = 0;
184: int part = 0;
185: double startValue = 0;
186: double oldStartValue = Double.NaN;
187: boolean inQuote = false;
188: for (int i = 0; i < newPattern.length(); ++i) {
189: char ch = newPattern.charAt(i);
190: if (ch == '\'') {
191: // Check for "''" indicating a literal quote
192: if ((i + 1) < newPattern.length()
193: && newPattern.charAt(i + 1) == ch) {
194: segments[part].append(ch);
195: ++i;
196: } else {
197: inQuote = !inQuote;
198: }
199: } else if (inQuote) {
200: segments[part].append(ch);
201: } else if (ch == '<' || ch == '#' || ch == '\u2264') {
202: if (segments[0].equals("")) {
203: throw new IllegalArgumentException();
204: }
205: try {
206: String tempBuffer = segments[0].toString();
207: if (tempBuffer.equals("\u221E")) {
208: startValue = Double.POSITIVE_INFINITY;
209: } else if (tempBuffer.equals("-\u221E")) {
210: startValue = Double.NEGATIVE_INFINITY;
211: } else {
212: startValue = Double.valueOf(
213: segments[0].toString()).doubleValue();
214: }
215: } catch (Exception e) {
216: throw new IllegalArgumentException();
217: }
218: if (ch == '<' && startValue != Double.POSITIVE_INFINITY
219: && startValue != Double.NEGATIVE_INFINITY) {
220: startValue = nextDouble(startValue);
221: }
222: if (startValue <= oldStartValue) {
223: throw new IllegalArgumentException();
224: }
225: segments[0].setLength(0);
226: part = 1;
227: } else if (ch == '|') {
228: if (count == newChoiceLimits.length) {
229: newChoiceLimits = doubleArraySize(newChoiceLimits);
230: newChoiceFormats = doubleArraySize(newChoiceFormats);
231: }
232: newChoiceLimits[count] = startValue;
233: newChoiceFormats[count] = segments[1].toString();
234: ++count;
235: oldStartValue = startValue;
236: segments[1].setLength(0);
237: part = 0;
238: } else {
239: segments[part].append(ch);
240: }
241: }
242: // clean up last one
243: if (part == 1) {
244: if (count == newChoiceLimits.length) {
245: newChoiceLimits = doubleArraySize(newChoiceLimits);
246: newChoiceFormats = doubleArraySize(newChoiceFormats);
247: }
248: newChoiceLimits[count] = startValue;
249: newChoiceFormats[count] = segments[1].toString();
250: ++count;
251: }
252: choiceLimits = new double[count];
253: System.arraycopy(newChoiceLimits, 0, choiceLimits, 0, count);
254: choiceFormats = new String[count];
255: System.arraycopy(newChoiceFormats, 0, choiceFormats, 0, count);
256: }
257:
258: /**
259: * Gets the pattern.
260: */
261: public String toPattern() {
262: StringBuffer result = new StringBuffer();
263: for (int i = 0; i < choiceLimits.length; ++i) {
264: if (i != 0) {
265: result.append('|');
266: }
267: // choose based upon which has less precision
268: // approximate that by choosing the closest one to an integer.
269: // could do better, but it's not worth it.
270: double less = previousDouble(choiceLimits[i]);
271: double tryLessOrEqual = Math.abs(Math.IEEEremainder(
272: choiceLimits[i], 1.0d));
273: double tryLess = Math.abs(Math.IEEEremainder(less, 1.0d));
274:
275: if (tryLessOrEqual < tryLess) {
276: result.append("" + choiceLimits[i]);
277: result.append('#');
278: } else {
279: if (choiceLimits[i] == Double.POSITIVE_INFINITY) {
280: result.append("\u221E");
281: } else if (choiceLimits[i] == Double.NEGATIVE_INFINITY) {
282: result.append("-\u221E");
283: } else {
284: result.append("" + less);
285: }
286: result.append('<');
287: }
288: // Append choiceFormats[i], using quotes if there are special characters.
289: // Single quotes themselves must be escaped in either case.
290: String text = choiceFormats[i];
291: boolean needQuote = text.indexOf('<') >= 0
292: || text.indexOf('#') >= 0
293: || text.indexOf('\u2264') >= 0
294: || text.indexOf('|') >= 0;
295: if (needQuote)
296: result.append('\'');
297: if (text.indexOf('\'') < 0)
298: result.append(text);
299: else {
300: for (int j = 0; j < text.length(); ++j) {
301: char c = text.charAt(j);
302: result.append(c);
303: if (c == '\'')
304: result.append(c);
305: }
306: }
307: if (needQuote)
308: result.append('\'');
309: }
310: return result.toString();
311: }
312:
313: /**
314: * Constructs with limits and corresponding formats based on the pattern.
315: * @see #applyPattern
316: */
317: public ChoiceFormat(String newPattern) {
318: applyPattern(newPattern);
319: }
320:
321: /**
322: * Constructs with the limits and the corresponding formats.
323: * @see #setChoices
324: */
325: public ChoiceFormat(double[] limits, String[] formats) {
326: setChoices(limits, formats);
327: }
328:
329: /**
330: * Set the choices to be used in formatting.
331: * @param limits contains the top value that you want
332: * parsed with that format,and should be in ascending sorted order. When
333: * formatting X, the choice will be the i, where
334: * limit[i] <= X < limit[i+1].
335: * If the limit array is not in ascending order, the results of formatting
336: * will be incorrect.
337: * @param formats are the formats you want to use for each limit.
338: * They can be either Format objects or Strings.
339: * When formatting with object Y,
340: * if the object is a NumberFormat, then ((NumberFormat) Y).format(X)
341: * is called. Otherwise Y.toString() is called.
342: */
343: public void setChoices(double[] limits, String formats[]) {
344: if (limits.length != formats.length) {
345: throw new IllegalArgumentException(
346: "Array and limit arrays must be of the same length.");
347: }
348: choiceLimits = limits;
349: choiceFormats = formats;
350: }
351:
352: /**
353: * Get the limits passed in the constructor.
354: * @return the limits.
355: */
356: public double[] getLimits() {
357: return choiceLimits;
358: }
359:
360: /**
361: * Get the formats passed in the constructor.
362: * @return the formats.
363: */
364: public Object[] getFormats() {
365: return choiceFormats;
366: }
367:
368: // Overrides
369:
370: /**
371: * Specialization of format. This method really calls
372: * <code>format(double, StringBuffer, FieldPosition)</code>
373: * thus the range of longs that are supported is only equal to
374: * the range that can be stored by double. This will never be
375: * a practical limitation.
376: */
377: public StringBuffer format(long number, StringBuffer toAppendTo,
378: FieldPosition status) {
379: return format((double) number, toAppendTo, status);
380: }
381:
382: /**
383: * Returns pattern with formatted double.
384: * @param number number to be formatted & substituted.
385: * @param toAppendTo where text is appended.
386: * @param status ignore no useful status is returned.
387: */
388: public StringBuffer format(double number, StringBuffer toAppendTo,
389: FieldPosition status) {
390: // find the number
391: int i;
392: for (i = 0; i < choiceLimits.length; ++i) {
393: if (!(number >= choiceLimits[i])) {
394: // same as number < choiceLimits, except catchs NaN
395: break;
396: }
397: }
398: --i;
399: if (i < 0)
400: i = 0;
401: // return either a formatted number, or a string
402: return toAppendTo.append(choiceFormats[i]);
403: }
404:
405: /**
406: * Parses a Number from the input text.
407: * @param text the source text.
408: * @param status an input-output parameter. On input, the
409: * status.index field indicates the first character of the
410: * source text that should be parsed. On exit, if no error
411: * occured, status.index is set to the first unparsed character
412: * in the source text. On exit, if an error did occur,
413: * status.index is unchanged and status.errorIndex is set to the
414: * first index of the character that caused the parse to fail.
415: * @return A Number representing the value of the number parsed.
416: */
417: public Number parse(String text, ParsePosition status) {
418: // find the best number (defined as the one with the longest parse)
419: int start = status.index;
420: int furthest = start;
421: double bestNumber = Double.NaN;
422: double tempNumber = 0.0;
423: for (int i = 0; i < choiceFormats.length; ++i) {
424: String tempString = choiceFormats[i];
425: if (text.regionMatches(start, tempString, 0, tempString
426: .length())) {
427: status.index = start + tempString.length();
428: tempNumber = choiceLimits[i];
429: if (status.index > furthest) {
430: furthest = status.index;
431: bestNumber = tempNumber;
432: if (furthest == text.length())
433: break;
434: }
435: }
436: }
437: status.index = furthest;
438: if (status.index == start) {
439: status.errorIndex = furthest;
440: }
441: return new Double(bestNumber);
442: }
443:
444: /**
445: * Finds the least double greater than d.
446: * If NaN, returns same value.
447: * <p>Used to make half-open intervals.
448: * @see #previousDouble
449: */
450: public static final double nextDouble(double d) {
451: return nextDouble(d, true);
452: }
453:
454: /**
455: * Finds the greatest double less than d.
456: * If NaN, returns same value.
457: * @see #nextDouble
458: */
459: public static final double previousDouble(double d) {
460: return nextDouble(d, false);
461: }
462:
463: /**
464: * Overrides Cloneable
465: */
466: public Object clone() {
467: ChoiceFormat other = (ChoiceFormat) super .clone();
468: // for primitives or immutables, shallow clone is enough
469: other.choiceLimits = (double[]) choiceLimits.clone();
470: other.choiceFormats = (String[]) choiceFormats.clone();
471: return other;
472: }
473:
474: /**
475: * Generates a hash code for the message format object.
476: */
477: public int hashCode() {
478: int result = choiceLimits.length;
479: if (choiceFormats.length > 0) {
480: // enough for reasonable distribution
481: result ^= choiceFormats[choiceFormats.length - 1]
482: .hashCode();
483: }
484: return result;
485: }
486:
487: /**
488: * Equality comparision between two
489: */
490: public boolean equals(Object obj) {
491: if (obj == null)
492: return false;
493: if (this == obj) // quick check
494: return true;
495: if (getClass() != obj.getClass())
496: return false;
497: ChoiceFormat other = (ChoiceFormat) obj;
498: return (Utility.arrayEquals(choiceLimits, other.choiceLimits) && Utility
499: .arrayEquals(choiceFormats, other.choiceFormats));
500: }
501:
502: /**
503: * After reading an object from the input stream, do a simple verification
504: * to maintain class invariants.
505: * @throws InvalidObjectException if the objects read from the stream is invalid.
506: */
507: private void readObject(ObjectInputStream in) throws IOException,
508: ClassNotFoundException {
509: in.defaultReadObject();
510: if (choiceLimits.length != choiceFormats.length) {
511: throw new InvalidObjectException(
512: "limits and format arrays of different length.");
513: }
514: }
515:
516: // ===============privates===========================
517:
518: /**
519: * A list of lower bounds for the choices. The formatter will return
520: * <code>choiceFormats[i]</code> if the number being formatted is greater than or equal to
521: * <code>choiceLimits[i]</code> and less than <code>choiceLimits[i+1]</code>.
522: * @serial
523: */
524: private double[] choiceLimits;
525:
526: /**
527: * A list of choice strings. The formatter will return
528: * <code>choiceFormats[i]</code> if the number being formatted is greater than or equal to
529: * <code>choiceLimits[i]</code> and less than <code>choiceLimits[i+1]</code>.
530: * @serial
531: */
532: private String[] choiceFormats;
533:
534: /*
535: static final long SIGN = 0x8000000000000000L;
536: static final long EXPONENT = 0x7FF0000000000000L;
537: static final long SIGNIFICAND = 0x000FFFFFFFFFFFFFL;
538:
539: private static double nextDouble (double d, boolean positive) {
540: if (Double.isNaN(d) || Double.isInfinite(d)) {
541: return d;
542: }
543: long bits = Double.doubleToLongBits(d);
544: long significand = bits & SIGNIFICAND;
545: if (bits < 0) {
546: significand |= (SIGN | EXPONENT);
547: }
548: long exponent = bits & EXPONENT;
549: if (positive) {
550: significand += 1;
551: // (should check for overflow & underflow )
552: } else {
553: significand -= 1;
554: // (should check for overflow & underflow )
555: }
556: bits = exponent | (significand & ~EXPONENT);
557: return Double.longBitsToDouble(bits);
558: }
559: */
560:
561: static final long SIGN = 0x8000000000000000L;
562: static final long EXPONENT = 0x7FF0000000000000L;
563: static final long POSITIVEINFINITY = 0x7FF0000000000000L;
564:
565: /**
566: * Finds the least double greater than d (if positive == true),
567: * or the greatest double less than d (if positive == false).
568: * If NaN, returns same value.
569: *
570: * Does not affect floating-point flags,
571: * provided these member functions do not:
572: * Double.longBitsToDouble(long)
573: * Double.doubleToLongBits(double)
574: * Double.isNaN(double)
575: */
576: public static double nextDouble(double d, boolean positive) {
577:
578: /* filter out NaN's */
579: if (Double.isNaN(d)) {
580: return d;
581: }
582:
583: /* zero's are also a special case */
584: if (d == 0.0) {
585: double smallestPositiveDouble = Double.longBitsToDouble(1L);
586: if (positive) {
587: return smallestPositiveDouble;
588: } else {
589: return -smallestPositiveDouble;
590: }
591: }
592:
593: /* if entering here, d is a nonzero value */
594:
595: /* hold all bits in a long for later use */
596: long bits = Double.doubleToLongBits(d);
597:
598: /* strip off the sign bit */
599: long magnitude = bits & ~SIGN;
600:
601: /* if next double away from zero, increase magnitude */
602: if ((bits > 0) == positive) {
603: if (magnitude != POSITIVEINFINITY) {
604: magnitude += 1;
605: }
606: }
607: /* else decrease magnitude */
608: else {
609: magnitude -= 1;
610: }
611:
612: /* restore sign bit and return */
613: long signbit = bits & SIGN;
614: return Double.longBitsToDouble(magnitude | signbit);
615: }
616:
617: private static double[] doubleArraySize(double[] array) {
618: int oldSize = array.length;
619: double[] newArray = new double[oldSize * 2];
620: System.arraycopy(array, 0, newArray, 0, oldSize);
621: return newArray;
622: }
623:
624: private String[] doubleArraySize(String[] array) {
625: int oldSize = array.length;
626: String[] newArray = new String[oldSize * 2];
627: System.arraycopy(array, 0, newArray, 0, oldSize);
628: return newArray;
629: }
630:
631: }
|