/**
* A formatter for Measure objects.
*
- * <p>To format a Measure object, first create a formatter
- * object using a MeasureFormat factory method. Then use that
- * object's format or formatMeasures methods.
+ * <p>
+ * To format a Measure object, first create a formatter object using a MeasureFormat factory method. Then
+ * use that object's format or formatMeasures methods.
*
* Here is sample code:
- * <pre>
- * MeasureFormat fmtFr = MeasureFormat.getInstance(
- * ULocale.FRENCH, FormatWidth.SHORT);
- * Measure measure = new Measure(23, MeasureUnit.CELSIUS);
*
- * // Output: 23 °C
- * System.out.println(fmtFr.format(measure));
+ * <pre>
+ * MeasureFormat fmtFr = MeasureFormat.getInstance(ULocale.FRENCH, FormatWidth.SHORT);
+ * Measure measure = new Measure(23, MeasureUnit.CELSIUS);
*
- * Measure measureF = new Measure(70, MeasureUnit.FAHRENHEIT);
+ * // Output: 23 °C
+ * System.out.println(fmtFr.format(measure));
*
- * // Output: 70 °F
- * System.out.println(fmtFr.format(measureF));
+ * Measure measureF = new Measure(70, MeasureUnit.FAHRENHEIT);
*
- * MeasureFormat fmtFrFull = MeasureFormat.getInstance(
- * ULocale.FRENCH, FormatWidth.WIDE);
- * // Output: 70 pieds et 5,3 pouces
- * System.out.println(fmtFrFull.formatMeasures(
- * new Measure(70, MeasureUnit.FOOT),
- * new Measure(5.3, MeasureUnit.INCH)));
+ * // Output: 70 °F
+ * System.out.println(fmtFr.format(measureF));
*
- * // Output: 1 pied et 1 pouce
- * System.out.println(fmtFrFull.formatMeasures(
- * new Measure(1, MeasureUnit.FOOT),
- * new Measure(1, MeasureUnit.INCH)));
+ * MeasureFormat fmtFrFull = MeasureFormat.getInstance(ULocale.FRENCH, FormatWidth.WIDE);
+ * // Output: 70 pieds et 5,3 pouces
+ * System.out.println(fmtFrFull.formatMeasures(new Measure(70, MeasureUnit.FOOT),
+ * new Measure(5.3, MeasureUnit.INCH)));
*
- * MeasureFormat fmtFrNarrow = MeasureFormat.getInstance(
- ULocale.FRENCH, FormatWidth.NARROW);
- * // Output: 1′ 1″
- * System.out.println(fmtFrNarrow.formatMeasures(
- * new Measure(1, MeasureUnit.FOOT),
- * new Measure(1, MeasureUnit.INCH)));
+ * // Output: 1 pied et 1 pouce
+ * System.out.println(
+ * fmtFrFull.formatMeasures(new Measure(1, MeasureUnit.FOOT), new Measure(1, MeasureUnit.INCH)));
*
+ * MeasureFormat fmtFrNarrow = MeasureFormat.getInstance(ULocale.FRENCH, FormatWidth.NARROW);
+ * // Output: 1′ 1″
+ * System.out.println(fmtFrNarrow.formatMeasures(new Measure(1, MeasureUnit.FOOT),
+ * new Measure(1, MeasureUnit.INCH)));
*
- * MeasureFormat fmtEn = MeasureFormat.getInstance(ULocale.ENGLISH, FormatWidth.WIDE);
+ * MeasureFormat fmtEn = MeasureFormat.getInstance(ULocale.ENGLISH, FormatWidth.WIDE);
*
- * // Output: 1 inch, 2 feet
- * fmtEn.formatMeasures(
- * new Measure(1, MeasureUnit.INCH),
- * new Measure(2, MeasureUnit.FOOT));
+ * // Output: 1 inch, 2 feet
+ * fmtEn.formatMeasures(new Measure(1, MeasureUnit.INCH), new Measure(2, MeasureUnit.FOOT));
* </pre>
* <p>
- * This class does not do conversions from one unit to another. It simply formats
- * whatever units it is given
+ * This class does not do conversions from one unit to another. It simply formats whatever units it is
+ * given
* <p>
- * This class is immutable and thread-safe so long as its deprecated subclass,
- * TimeUnitFormat, is never used. TimeUnitFormat is not thread-safe, and is
- * mutable. Although this class has existing subclasses, this class does not support new
- * sub-classes.
+ * This class is immutable and thread-safe so long as its deprecated subclass, TimeUnitFormat, is never
+ * used. TimeUnitFormat is not thread-safe, and is mutable. Although this class has existing subclasses,
+ * this class does not support new sub-classes.
*
* @see com.ibm.icu.text.UFormat
* @author Alan Liu
*/
public class MeasureFormat extends UFormat {
-
// Generated by serialver from JDK 1.4.1_01
static final long serialVersionUID = -7182021401701778240L;
private final transient ImmutableNumberFormat integerFormat;
- private static final SimpleCache<ULocale, MeasureFormatData> localeMeasureFormatData
- = new SimpleCache<ULocale, MeasureFormatData>();
+ private static final SimpleCache<ULocale, MeasureFormatData> localeMeasureFormatData = new SimpleCache<ULocale, MeasureFormatData>();
- private static final SimpleCache<ULocale, NumericFormatters> localeToNumericDurationFormatters
- = new SimpleCache<ULocale,NumericFormatters>();
+ private static final SimpleCache<ULocale, NumericFormatters> localeToNumericDurationFormatters = new SimpleCache<ULocale, NumericFormatters>();
- private static final Map<MeasureUnit, Integer> hmsTo012 =
- new HashMap<MeasureUnit, Integer>();
+ private static final Map<MeasureUnit, Integer> hmsTo012 = new HashMap<MeasureUnit, Integer>();
static {
hmsTo012.put(MeasureUnit.HOUR, 0);
NARROW(ListFormatter.Style.DURATION_NARROW, NumberFormat.CURRENCYSTYLE),
/**
- * Identical to NARROW except when formatMeasures is called with
- * an hour and minute; minute and second; or hour, minute, and second Measures.
- * In these cases formatMeasures formats as 5:37:23 instead of 5h, 37m, 23s.
+ * Identical to NARROW except when formatMeasures is called with an hour and minute; minute and
+ * second; or hour, minute, and second Measures. In these cases formatMeasures formats as 5:37:23
+ * instead of 5h, 37m, 23s.
*
* @stable ICU 53
*/
// Be sure to update the toFormatWidth and fromFormatWidth() functions
// when adding an enum value.
- private static final int INDEX_COUNT = 3; // NARROW.ordinal() + 1
+ private static final int INDEX_COUNT = 3; // NARROW.ordinal() + 1
private final ListFormatter.Style listFormatterStyle;
private final int currencyStyle;
/**
* Create a format from the locale, formatWidth, and format.
*
- * @param locale the locale.
- * @param formatWidth hints how long formatted strings should be.
+ * @param locale
+ * the locale.
+ * @param formatWidth
+ * hints how long formatted strings should be.
* @return The new MeasureFormat object.
* @stable ICU 53
*/
/**
* Create a format from the {@link java.util.Locale} and formatWidth.
*
- * @param locale the {@link java.util.Locale}.
- * @param formatWidth hints how long formatted strings should be.
+ * @param locale
+ * the {@link java.util.Locale}.
+ * @param formatWidth
+ * hints how long formatted strings should be.
* @return The new MeasureFormat object.
* @stable ICU 54
*/
/**
* Create a format from the locale, formatWidth, and format.
*
- * @param locale the locale.
- * @param formatWidth hints how long formatted strings should be.
- * @param format This is defensively copied.
+ * @param locale
+ * the locale.
+ * @param formatWidth
+ * hints how long formatted strings should be.
+ * @param format
+ * This is defensively copied.
* @return The new MeasureFormat object.
* @stable ICU 53
*/
- public static MeasureFormat getInstance(ULocale locale, FormatWidth formatWidth, NumberFormat format) {
+ public static MeasureFormat getInstance(
+ ULocale locale,
+ FormatWidth formatWidth,
+ NumberFormat format) {
PluralRules rules = PluralRules.forLocale(locale);
NumericFormatters formatters = null;
MeasureFormatData data = localeMeasureFormatData.get(locale);
intFormat.setMaximumFractionDigits(0);
intFormat.setMinimumFractionDigits(0);
intFormat.setRoundingMode(BigDecimal.ROUND_DOWN);
- return new MeasureFormat(
- locale,
+ return new MeasureFormat(locale,
data,
formatWidth,
new ImmutableNumberFormat(format),
rules,
formatters,
- new ImmutableNumberFormat(NumberFormat.getInstance(locale, formatWidth.getCurrencyStyle())),
+ new ImmutableNumberFormat(
+ NumberFormat.getInstance(locale, formatWidth.getCurrencyStyle())),
new ImmutableNumberFormat(intFormat));
}
/**
* Create a format from the {@link java.util.Locale}, formatWidth, and format.
*
- * @param locale the {@link java.util.Locale}.
- * @param formatWidth hints how long formatted strings should be.
- * @param format This is defensively copied.
+ * @param locale
+ * the {@link java.util.Locale}.
+ * @param formatWidth
+ * hints how long formatted strings should be.
+ * @param format
+ * This is defensively copied.
* @return The new MeasureFormat object.
* @stable ICU 54
*/
- public static MeasureFormat getInstance(Locale locale, FormatWidth formatWidth, NumberFormat format) {
+ public static MeasureFormat getInstance(
+ Locale locale,
+ FormatWidth formatWidth,
+ NumberFormat format) {
return getInstance(ULocale.forLocale(locale), formatWidth, format);
}
/**
- * Able to format Collection<? extends Measure>, Measure[], and Measure
- * by delegating to formatMeasures.
- * If the pos argument identifies a NumberFormat field,
- * then its indices are set to the beginning and end of the first such field
- * encountered. MeasureFormat itself does not supply any fields.
+ * Able to format Collection<? extends Measure>, Measure[], and Measure by delegating to
+ * formatMeasures. If the pos argument identifies a NumberFormat field, then its indices are set to
+ * the beginning and end of the first such field encountered. MeasureFormat itself does not supply
+ * any fields.
*
- * Calling a
- * <code>formatMeasures</code> method is preferred over calling
- * this method as they give better performance.
+ * Calling a <code>formatMeasures</code> method is preferred over calling this method as they give
+ * better performance.
*
- * @param obj must be a Collection<? extends Measure>, Measure[], or Measure object.
- * @param toAppendTo Formatted string appended here.
- * @param pos Identifies a field in the formatted text.
+ * @param obj
+ * must be a Collection<? extends Measure>, Measure[], or Measure object.
+ * @param toAppendTo
+ * Formatted string appended here.
+ * @param pos
+ * Identifies a field in the formatted text.
* @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
*
* @stable ICU53
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
int prevLength = toAppendTo.length();
- FieldPosition fpos =
- new FieldPosition(pos.getFieldAttribute(), pos.getField());
+ FieldPosition fpos = new FieldPosition(pos.getFieldAttribute(), pos.getField());
if (obj instanceof Collection) {
Collection<?> coll = (Collection<?>) obj;
Measure[] measures = new Measure[coll.size()];
toAppendTo.append(formatMeasures(new StringBuilder(), fpos, measures));
} else if (obj instanceof Measure[]) {
toAppendTo.append(formatMeasures(new StringBuilder(), fpos, (Measure[]) obj));
- } else if (obj instanceof Measure){
+ } else if (obj instanceof Measure) {
toAppendTo.append(formatMeasure((Measure) obj, numberFormat, new StringBuilder(), fpos));
} else {
throw new IllegalArgumentException(obj.toString());
/**
* Parses text from a string to produce a <code>Measure</code>.
+ *
* @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition)
- * @throws UnsupportedOperationException Not supported.
+ * @throws UnsupportedOperationException
+ * Not supported.
* @draft ICU 53 (Retain)
* @provisional This API might change or be removed in a future release.
*/
}
/**
- * Format a sequence of measures. Uses the ListFormatter unit lists.
- * So, for example, one could format “3 feet, 2 inches”.
- * Zero values are formatted (eg, “3 feet, 0 inches”). It is the caller’s
- * responsibility to have the appropriate values in appropriate order,
- * and using the appropriate Number values. Typically the units should be
- * in descending order, with all but the last Measure having integer values
- * (eg, not “3.2 feet, 2 inches”).
+ * Format a sequence of measures. Uses the ListFormatter unit lists. So, for example, one could
+ * format “3 feet, 2 inches”. Zero values are formatted (eg, “3 feet, 0 inches”). It is the caller’s
+ * responsibility to have the appropriate values in appropriate order, and using the appropriate
+ * Number values. Typically the units should be in descending order, with all but the last Measure
+ * having integer values (eg, not “3.2 feet, 2 inches”).
*
- * @param measures a sequence of one or more measures.
+ * @param measures
+ * a sequence of one or more measures.
* @return the formatted string.
* @stable ICU 53
*/
public final String formatMeasures(Measure... measures) {
- return formatMeasures(
- new StringBuilder(),
- DontCareFieldPosition.INSTANCE,
- measures).toString();
+ return formatMeasures(new StringBuilder(), DontCareFieldPosition.INSTANCE, measures).toString();
}
/**
- * Format a range of measures, such as "3.4-5.1 meters". It is the caller’s
- * responsibility to have the appropriate values in appropriate order,
- * and using the appropriate Number values.
- * <br>Note: If the format doesn’t have enough decimals, or lowValue ≥ highValue,
- * the result will be a degenerate range, like “5-5 meters”.
- * <br>Currency Units are not yet supported.
+ * Format a range of measures, such as "3.4-5.1 meters". It is the caller’s responsibility to have
+ * the appropriate values in appropriate order, and using the appropriate Number values. <br>
+ * Note: If the format doesn’t have enough decimals, or lowValue ≥ highValue, the result will be a
+ * degenerate range, like “5-5 meters”. <br>
+ * Currency Units are not yet supported.
*
- * @param lowValue low value in range
- * @param highValue high value in range
+ * @param lowValue
+ * low value in range
+ * @param highValue
+ * high value in range
* @return the formatted string.
* @internal
* @deprecated This API is ICU internal only.
public final String formatMeasureRange(Measure lowValue, Measure highValue) {
MeasureUnit unit = lowValue.getUnit();
if (!unit.equals(highValue.getUnit())) {
- throw new IllegalArgumentException("Units must match: " + unit + " ≠ " + highValue.getUnit());
+ throw new IllegalArgumentException(
+ "Units must match: " + unit + " ≠ " + highValue.getUnit());
}
Number lowNumber = lowValue.getNumber();
Number highNumber = highValue.getNumber();
final double lowDouble = lowNumber.doubleValue();
String keywordLow = rules.select(new PluralRules.FixedDecimal(lowDouble,
- lowFpos.getCountVisibleFractionDigits(), lowFpos.getFractionDigits()));
+ lowFpos.getCountVisibleFractionDigits(),
+ lowFpos.getFractionDigits()));
final double highDouble = highNumber.doubleValue();
String keywordHigh = rules.select(new PluralRules.FixedDecimal(highDouble,
- highFpos.getCountVisibleFractionDigits(), highFpos.getFractionDigits()));
+ highFpos.getCountVisibleFractionDigits(),
+ highFpos.getFractionDigits()));
final PluralRanges pluralRanges = Factory.getDefaultFactory().getPluralRanges(getLocale());
- StandardPlural resolvedPlural = pluralRanges.get(
- StandardPlural.fromString(keywordLow),
+ StandardPlural resolvedPlural = pluralRanges.get(StandardPlural.fromString(keywordLow),
StandardPlural.fromString(keywordHigh));
String rangeFormatter = getRangeFormat(getLocale(), formatWidth);
- String formattedNumber = SimpleFormatterImpl.formatCompiledPattern(
- rangeFormatter, lowFormatted, highFormatted);
+ String formattedNumber = SimpleFormatterImpl
+ .formatCompiledPattern(rangeFormatter, lowFormatted, highFormatted);
if (isCurrency) {
// Nasty hack
Currency currencyUnit = (Currency) unit;
StringBuilder result = new StringBuilder();
- appendReplacingCurrency(currencyFormat.getPrefix(lowDouble >= 0), currencyUnit, resolvedPlural, result);
+ appendReplacingCurrency(currencyFormat.getPrefix(lowDouble >= 0),
+ currencyUnit,
+ resolvedPlural,
+ result);
result.append(formattedNumber);
- appendReplacingCurrency(currencyFormat.getSuffix(highDouble >= 0), currencyUnit, resolvedPlural, result);
+ appendReplacingCurrency(currencyFormat.getSuffix(highDouble >= 0),
+ currencyUnit,
+ resolvedPlural,
+ result);
return result.toString();
- // StringBuffer buffer = new StringBuffer();
- // CurrencyAmount currencyLow = (CurrencyAmount) lowValue;
- // CurrencyAmount currencyHigh = (CurrencyAmount) highValue;
- // FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
- // currencyFormat.format(currencyLow, buffer, pos);
- // int startOfInteger = pos.getBeginIndex();
- // StringBuffer buffer2 = new StringBuffer();
- // FieldPosition pos2 = new FieldPosition(0);
- // currencyFormat.format(currencyHigh, buffer2, pos2);
+ // StringBuffer buffer = new StringBuffer();
+ // CurrencyAmount currencyLow = (CurrencyAmount) lowValue;
+ // CurrencyAmount currencyHigh = (CurrencyAmount) highValue;
+ // FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
+ // currencyFormat.format(currencyLow, buffer, pos);
+ // int startOfInteger = pos.getBeginIndex();
+ // StringBuffer buffer2 = new StringBuffer();
+ // FieldPosition pos2 = new FieldPosition(0);
+ // currencyFormat.format(currencyHigh, buffer2, pos2);
} else {
- String formatter =
- getPluralFormatter(lowValue.getUnit(), formatWidth, resolvedPlural.ordinal());
+ String formatter = getPluralFormatter(lowValue.getUnit(),
+ formatWidth,
+ resolvedPlural.ordinal());
return SimpleFormatterImpl.formatCompiledPattern(formatter, formattedNumber);
}
}
- private void appendReplacingCurrency(String affix, Currency unit, StandardPlural resolvedPlural, StringBuilder result) {
+ private void appendReplacingCurrency(
+ String affix,
+ Currency unit,
+ StandardPlural resolvedPlural,
+ StringBuilder result) {
String replacement = "¤";
int pos = affix.indexOf(replacement);
if (pos < 0) {
result.append(affix);
} else {
// for now, just assume single
- result.append(affix.substring(0,pos));
+ result.append(affix.substring(0, pos));
// we have a mismatch between the number style and the currency style, so remap
int currentStyle = formatWidth.getCurrencyStyle();
if (currentStyle == NumberFormat.ISOCURRENCYSTYLE) {
result.append(unit.getCurrencyCode());
} else {
result.append(unit.getName(currencyFormat.nf.getLocale(ULocale.ACTUAL_LOCALE),
- currentStyle == NumberFormat.CURRENCYSTYLE ? Currency.SYMBOL_NAME : Currency.PLURAL_LONG_NAME,
- resolvedPlural.getKeyword(), null));
+ currentStyle == NumberFormat.CURRENCYSTYLE ? Currency.SYMBOL_NAME
+ : Currency.PLURAL_LONG_NAME,
+ resolvedPlural.getKeyword(),
+ null));
}
- result.append(affix.substring(pos+replacement.length()));
+ result.append(affix.substring(pos + replacement.length()));
}
}
*
* An example of such a formatted string is "3.5 meters per second."
*
- * @param measure the measure object. In above example, 3.5 meters.
- * @param perUnit the per unit. In above example, it is MeasureUnit.SECOND
- * @param appendTo formatted string appended here.
- * @param pos The field position.
+ * @param measure
+ * the measure object. In above example, 3.5 meters.
+ * @param perUnit
+ * the per unit. In above example, it is MeasureUnit.SECOND
+ * @param appendTo
+ * formatted string appended here.
+ * @param pos
+ * The field position.
* @return appendTo.
* @stable ICU 55
*/
MeasureUnit perUnit,
StringBuilder appendTo,
FieldPosition pos) {
- MeasureUnit resolvedUnit = MeasureUnit.resolveUnitPerUnit(
- measure.getUnit(), perUnit);
+ MeasureUnit resolvedUnit = MeasureUnit.resolveUnitPerUnit(measure.getUnit(), perUnit);
if (resolvedUnit != null) {
Measure newMeasure = new Measure(measure.getNumber(), resolvedUnit);
return formatMeasure(newMeasure, numberFormat, appendTo, pos);
}
- FieldPosition fpos = new FieldPosition(
- pos.getFieldAttribute(), pos.getField());
+ FieldPosition fpos = new FieldPosition(pos.getFieldAttribute(), pos.getField());
int offset = withPerUnitAndAppend(
formatMeasure(measure, numberFormat, new StringBuilder(), fpos),
perUnit,
/**
* Formats a sequence of measures.
*
- * If the fieldPosition argument identifies a NumberFormat field,
- * then its indices are set to the beginning and end of the first such field
- * encountered. MeasureFormat itself does not supply any fields.
+ * If the fieldPosition argument identifies a NumberFormat field, then its indices are set to the
+ * beginning and end of the first such field encountered. MeasureFormat itself does not supply any
+ * fields.
*
- * @param appendTo the formatted string appended here.
- * @param fieldPosition Identifies a field in the formatted text.
- * @param measures the measures to format.
+ * @param appendTo
+ * the formatted string appended here.
+ * @param fieldPosition
+ * Identifies a field in the formatted text.
+ * @param measures
+ * the measures to format.
* @return appendTo.
* @see MeasureFormat#formatMeasures(Measure...)
* @stable ICU 53
*/
public StringBuilder formatMeasures(
- StringBuilder appendTo, FieldPosition fieldPosition, Measure... measures) {
+ StringBuilder appendTo,
+ FieldPosition fieldPosition,
+ Measure... measures) {
// fast track for trivial cases
if (measures.length == 0) {
return appendTo;
}
}
- ListFormatter listFormatter = ListFormatter.getInstance(
- getLocale(), formatWidth.getListFormatterStyle());
+ ListFormatter listFormatter = ListFormatter.getInstance(getLocale(),
+ formatWidth.getListFormatterStyle());
if (fieldPosition != DontCareFieldPosition.INSTANCE) {
return formatMeasuresSlowTrack(listFormatter, appendTo, fieldPosition, measures);
}
// Fast track: No field position.
String[] results = new String[measures.length];
for (int i = 0; i < measures.length; i++) {
- results[i] = formatMeasure(
- measures[i],
+ results[i] = formatMeasure(measures[i],
i == measures.length - 1 ? numberFormat : integerFormat);
}
return appendTo.append(listFormatter.format((Object[]) results));
}
/**
- * Gets the display name of the specified {@link MeasureUnit} corresponding to the current
- * locale and format width.
- * @param unit The unit for which to get a display name.
- * @return The display name in the locale and width specified in
- * {@link MeasureFormat#getInstance}, or null if there is no display name available
- * for the specified unit.
+ * Gets the display name of the specified {@link MeasureUnit} corresponding to the current locale and
+ * format width.
+ *
+ * @param unit
+ * The unit for which to get a display name.
+ * @return The display name in the locale and width specified in {@link MeasureFormat#getInstance},
+ * or null if there is no display name available for the specified unit.
*
* @stable ICU 58
*/
}
/**
- * Two MeasureFormats, a and b, are equal if and only if they have the same formatWidth,
- * locale, and equal number formats.
+ * Two MeasureFormats, a and b, are equal if and only if they have the same formatWidth, locale, and
+ * equal number formats.
+ *
* @stable ICU 53
*/
@Override
/**
* {@inheritDoc}
+ *
* @stable ICU 53
*/
@Override
public final int hashCode() {
// A very slow but safe implementation.
- return (getLocale().hashCode() * 31
- + getNumberFormat().hashCode()) * 31 + getWidth().hashCode();
+ return (getLocale().hashCode() * 31 + getNumberFormat().hashCode()) * 31 + getWidth().hashCode();
}
/**
* Get the format width this instance is using.
+ *
* @stable ICU 53
*/
public MeasureFormat.FormatWidth getWidth() {
/**
* Get the locale of this instance.
+ *
* @stable ICU 53
*/
public final ULocale getLocale() {
/**
* Get a copy of the number format.
+ *
* @stable ICU 53
*/
public NumberFormat getNumberFormat() {
}
/**
- * Return a formatter for CurrencyAmount objects in the given
- * locale.
- * @param locale desired locale
+ * Return a formatter for CurrencyAmount objects in the given locale.
+ *
+ * @param locale
+ * desired locale
* @return a formatter object
* @stable ICU 3.0
*/
}
/**
- * Return a formatter for CurrencyAmount objects in the given
- * {@link java.util.Locale}.
- * @param locale desired {@link java.util.Locale}
+ * Return a formatter for CurrencyAmount objects in the given {@link java.util.Locale}.
+ *
+ * @param locale
+ * desired {@link java.util.Locale}
* @return a formatter object
* @stable ICU 54
*/
}
/**
- * Return a formatter for CurrencyAmount objects in the default
- * <code>FORMAT</code> locale.
+ * Return a formatter for CurrencyAmount objects in the default <code>FORMAT</code> locale.
+ *
* @return a formatter object
* @see Category#FORMAT
* @stable ICU 3.0
}
MeasureFormat withNumberFormat(NumberFormat format) {
- return new MeasureFormat(
- getLocale(),
+ return new MeasureFormat(getLocale(),
this.cache,
this.formatWidth,
new ImmutableNumberFormat(format),
this.hourMinuteSecond = hourMinuteSecond;
}
- public DateFormat getHourMinute() { return hourMinute; }
- public DateFormat getMinuteSecond() { return minuteSecond; }
- public DateFormat getHourMinuteSecond() { return hourMinuteSecond; }
+ public DateFormat getHourMinute() {
+ return hourMinute;
+ }
+
+ public DateFormat getMinuteSecond() {
+ return minuteSecond;
+ }
+
+ public DateFormat getHourMinuteSecond() {
+ return hourMinuteSecond;
+ }
}
- private static NumericFormatters loadNumericFormatters(
- ULocale locale) {
- ICUResourceBundle r = (ICUResourceBundle)UResourceBundle.
- getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
- return new NumericFormatters(
- loadNumericDurationFormat(r, "hm"),
+ private static NumericFormatters loadNumericFormatters(ULocale locale) {
+ ICUResourceBundle r = (ICUResourceBundle) UResourceBundle
+ .getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
+ return new NumericFormatters(loadNumericDurationFormat(r, "hm"),
loadNumericDurationFormat(r, "ms"),
loadNumericDurationFormat(r, "hms"));
}
/**
- * Sink for enumerating all of the measurement unit display names.
- * Contains inner sink classes, each one corresponding to a type of resource table.
- * The outer sink handles the top-level units, unitsNarrow, and unitsShort tables.
+ * Sink for enumerating all of the measurement unit display names. Contains inner sink classes, each
+ * one corresponding to a type of resource table. The outer sink handles the top-level units,
+ * unitsNarrow, and unitsShort tables.
*
- * More specific bundles (en_GB) are enumerated before their parents (en_001, en, root):
- * Only store a value if it is still missing, that is, it has not been overridden.
+ * More specific bundles (en_GB) are enumerated before their parents (en_001, en, root): Only store a
+ * value if it is still missing, that is, it has not been overridden.
*
- * C++: Each inner sink class has a reference to the main outer sink.
- * Java: Use non-static inner classes instead.
+ * C++: Each inner sink class has a reference to the main outer sink. Java: Use non-static inner
+ * classes instead.
*/
private static final class UnitDataSink extends UResource.Sink {
void setFormatterIfAbsent(int index, UResource.Value value, int minPlaceholders) {
if (patterns == null) {
- EnumMap<FormatWidth, String[]> styleToPatterns =
- cacheData.unitToStyleToPatterns.get(unit);
+ EnumMap<FormatWidth, String[]> styleToPatterns = cacheData.unitToStyleToPatterns
+ .get(unit);
if (styleToPatterns == null) {
- styleToPatterns =
- new EnumMap<FormatWidth, String[]>(FormatWidth.class);
+ styleToPatterns = new EnumMap<FormatWidth, String[]>(FormatWidth.class);
cacheData.unitToStyleToPatterns.put(unit, styleToPatterns);
} else {
patterns = styleToPatterns.get(width);
}
}
if (patterns[index] == null) {
- patterns[index] = SimpleFormatterImpl.compileToStringMinMaxArguments(
- value.getString(), sb, minPlaceholders, 1);
+ patterns[index] = SimpleFormatterImpl
+ .compileToStringMinMaxArguments(value.getString(), sb, minPlaceholders, 1);
}
}
}
/**
- * Consume a display pattern. For example,
- * unitsShort/duration/hour contains other{"{0} hrs"}.
+ * Consume a display pattern. For example, unitsShort/duration/hour contains other{"{0} hrs"}.
*/
void consumePattern(UResource.Key key, UResource.Value value) {
if (key.contentEquals("dnam")) {
}
/**
- * Consume a table of per-unit tables. For example,
- * unitsShort/duration contains tables for duration-unit subtypes day & hour.
+ * Consume a table of per-unit tables. For example, unitsShort/duration contains tables for
+ * duration-unit subtypes day & hour.
*/
void consumeSubtypeTable(UResource.Key key, UResource.Value value) {
- unit = MeasureUnit.internalGetInstance(type, key.toString()); // never null
+ unit = MeasureUnit.internalGetInstance(type, key.toString()); // never null
// Trigger a fresh lookup of the patterns for this unit+width.
patterns = null;
}
/**
- * Consume compound x-per-y display pattern. For example,
- * unitsShort/compound/per may be "{0}/{1}".
+ * Consume compound x-per-y display pattern. For example, unitsShort/compound/per may be
+ * "{0}/{1}".
*/
void consumeCompoundPattern(UResource.Key key, UResource.Value value) {
if (key.contentEquals("per")) {
cacheData.styleToPerPattern.put(width,
- SimpleFormatterImpl.compileToStringMinMaxArguments(
- value.getString(), sb, 2, 2));
+ SimpleFormatterImpl.compileToStringMinMaxArguments(value.getString(), sb, 2, 2));
}
}
/**
- * Consume a table of unit type tables. For example,
- * unitsShort contains tables for area & duration.
- * It also contains a table for the compound/per pattern.
+ * Consume a table of unit type tables. For example, unitsShort contains tables for area &
+ * duration. It also contains a table for the compound/per pattern.
*/
void consumeUnitTypesTable(UResource.Key key, UResource.Value value) {
if (key.contentEquals("currency")) {
FormatWidth targetWidth = widthFromAlias(value);
if (targetWidth == null) {
// We do not recognize what to fall back to.
- throw new ICUException("Units data fallback from " + key +
- " to unknown " + value.getAliasString());
+ throw new ICUException(
+ "Units data fallback from " + key + " to unknown " + value.getAliasString());
}
// Check that we do not fall back to another fallback.
if (cacheData.widthFallback[targetWidth.ordinal()] != null) {
- throw new ICUException("Units data fallback from " + key +
- " to " + value.getAliasString() + " which falls back to something else");
+ throw new ICUException("Units data fallback from "
+ + key
+ + " to "
+ + value.getAliasString()
+ + " which falls back to something else");
}
cacheData.widthFallback[sourceWidth.ordinal()] = targetWidth;
}
* Returns formatting data for all MeasureUnits except for currency ones.
*/
private static MeasureFormatData loadLocaleData(ULocale locale) {
- ICUResourceBundle resource =
- (ICUResourceBundle)UResourceBundle.getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
+ ICUResourceBundle resource = (ICUResourceBundle) UResourceBundle
+ .getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
MeasureFormatData cacheData = new MeasureFormatData();
UnitDataSink sink = new UnitDataSink(cacheData);
resource.getAllItemsWithFallback("", sink);
if (pattern == null) {
throw new MissingResourceException(
"no formatting pattern for " + unit + ", width " + width + ", index " + index,
- null, null);
+ null,
+ null);
}
return pattern;
}
}
private int withPerUnitAndAppend(
- CharSequence formatted, MeasureUnit perUnit, StringBuilder appendTo) {
+ CharSequence formatted,
+ MeasureUnit perUnit,
+ StringBuilder appendTo) {
int[] offsets = new int[1];
- String perUnitPattern =
- getFormatterOrNull(perUnit, formatWidth, MeasureFormatData.PER_UNIT_INDEX);
+ String perUnitPattern = getFormatterOrNull(perUnit,
+ formatWidth,
+ MeasureFormatData.PER_UNIT_INDEX);
if (perUnitPattern != null) {
SimpleFormatterImpl.formatAndAppend(perUnitPattern, appendTo, offsets, formatted);
return offsets[0];
String perPattern = getPerFormatter(formatWidth);
String pattern = getPluralFormatter(perUnit, formatWidth, StandardPlural.ONE.ordinal());
String perUnitString = SimpleFormatterImpl.getTextWithNoArguments(pattern).trim();
- SimpleFormatterImpl.formatAndAppend(
- perPattern, appendTo, offsets, formatted, perUnitString);
+ SimpleFormatterImpl.formatAndAppend(perPattern, appendTo, offsets, formatted, perUnitString);
return offsets[0];
}
private String formatMeasure(Measure measure, ImmutableNumberFormat nf) {
- return formatMeasure(
- measure, nf, new StringBuilder(),
- DontCareFieldPosition.INSTANCE).toString();
+ return formatMeasure(measure, nf, new StringBuilder(), DontCareFieldPosition.INSTANCE)
+ .toString();
}
private StringBuilder formatMeasure(
Number n = measure.getNumber();
MeasureUnit unit = measure.getUnit();
if (unit instanceof Currency) {
- return appendTo.append(
- currencyFormat.format(
- new CurrencyAmount(n, (Currency) unit),
- new StringBuffer(),
- fieldPosition));
+ return appendTo.append(currencyFormat
+ .format(new CurrencyAmount(n, (Currency) unit), new StringBuffer(), fieldPosition));
}
StringBuffer formattedNumber = new StringBuffer();
- StandardPlural pluralForm = QuantityFormatter.selectPlural(
- n, nf.nf, rules, formattedNumber, fieldPosition);
+ StandardPlural pluralForm = QuantityFormatter
+ .selectPlural(n, nf.nf, rules, formattedNumber, fieldPosition);
String formatter = getPluralFormatter(unit, formatWidth, pluralForm.ordinal());
return QuantityFormatter.format(formatter, formattedNumber, appendTo, fieldPosition);
}
/**
- * Instances contain all MeasureFormat specific data for a particular locale.
- * This data is cached. It is never copied, but is shared via shared pointers.
+ * Instances contain all MeasureFormat specific data for a particular locale. This data is cached. It
+ * is never copied, but is shared via shared pointers.
*
- * Note: We might change the cache data to have
- * an array[WIDTH_INDEX_COUNT] or EnumMap<FormatWidth, ...> of
- * complete sets of unit & per patterns,
- * to correspond to the resource data and its aliases.
+ * Note: We might change the cache data to have an array[WIDTH_INDEX_COUNT] or EnumMap<FormatWidth,
+ * ...> of complete sets of unit & per patterns, to correspond to the resource data and its aliases.
*/
private static final class MeasureFormatData {
static final int PER_UNIT_INDEX = StandardPlural.COUNT;
}
/**
- * Redirection data from root-bundle, top-level sideways aliases.
- * - null: initial value, just fall back to root
- * - FormatWidth.WIDE/SHORT/NARROW: sideways alias for missing data
+ * Redirection data from root-bundle, top-level sideways aliases. - null: initial value, just
+ * fall back to root - FormatWidth.WIDE/SHORT/NARROW: sideways alias for missing data
*/
final FormatWidth widthFallback[] = new FormatWidth[FormatWidth.INDEX_COUNT];
- /** Measure unit -> format width -> array of patterns ("{0} meters") (plurals + PER_UNIT_INDEX) */
- final Map<MeasureUnit, EnumMap<FormatWidth, String[]>> unitToStyleToPatterns =
- new HashMap<MeasureUnit, EnumMap<FormatWidth, String[]>>();
- final Map<MeasureUnit, EnumMap<FormatWidth, String>> unitToStyleToDnam =
- new HashMap<MeasureUnit, EnumMap<FormatWidth, String>>();
- final EnumMap<FormatWidth, String> styleToPerPattern =
- new EnumMap<FormatWidth, String>(FormatWidth.class);;
+ /**
+ * Measure unit -> format width -> array of patterns ("{0} meters") (plurals + PER_UNIT_INDEX)
+ */
+ final Map<MeasureUnit, EnumMap<FormatWidth, String[]>> unitToStyleToPatterns = new HashMap<MeasureUnit, EnumMap<FormatWidth, String[]>>();
+ final Map<MeasureUnit, EnumMap<FormatWidth, String>> unitToStyleToDnam = new HashMap<MeasureUnit, EnumMap<FormatWidth, String>>();
+ final EnumMap<FormatWidth, String> styleToPerPattern = new EnumMap<FormatWidth, String>(
+ FormatWidth.class);;
}
// Wrapper around NumberFormat that provides immutability and thread-safety.
return (NumberFormat) nf.clone();
}
- public synchronized StringBuffer format(
- Number n, StringBuffer buffer, FieldPosition pos) {
+ public synchronized StringBuffer format(Number n, StringBuffer buffer, FieldPosition pos) {
return nf.format(n, buffer, pos);
}
public synchronized StringBuffer format(
- CurrencyAmount n, StringBuffer buffer, FieldPosition pos) {
+ CurrencyAmount n,
+ StringBuffer buffer,
+ FieldPosition pos) {
return nf.format(n, buffer, pos);
}
}
public String getPrefix(boolean positive) {
- return positive ? ((DecimalFormat)nf).getPositivePrefix() : ((DecimalFormat)nf).getNegativePrefix();
+ return positive ? ((DecimalFormat) nf).getPositivePrefix()
+ : ((DecimalFormat) nf).getNegativePrefix();
}
+
public String getSuffix(boolean positive) {
- return positive ? ((DecimalFormat)nf).getPositiveSuffix() : ((DecimalFormat)nf).getNegativeSuffix();
+ return positive ? ((DecimalFormat) nf).getPositiveSuffix()
+ : ((DecimalFormat) nf).getNegativeSuffix();
}
}
static final class PatternData {
final String prefix;
final String suffix;
+
public PatternData(String pattern) {
int pos = pattern.indexOf("{0}");
if (pos < 0) {
prefix = pattern;
suffix = null;
} else {
- prefix = pattern.substring(0,pos);
- suffix = pattern.substring(pos+3);
+ prefix = pattern.substring(0, pos);
+ suffix = pattern.substring(pos + 3);
}
}
+
@Override
public String toString() {
return prefix + "; " + suffix;
String[] results = new String[measures.length];
// Zero out our field position so that we can tell when we find our field.
- FieldPosition fpos = new FieldPosition(
- fieldPosition.getFieldAttribute(), fieldPosition.getField());
+ FieldPosition fpos = new FieldPosition(fieldPosition.getFieldAttribute(),
+ fieldPosition.getField());
int fieldPositionFoundIndex = -1;
for (int i = 0; i < measures.length; ++i) {
results[i] = formatMeasure(measures[i], nf);
}
}
- ListFormatter.FormattedListBuilder builder =
- listFormatter.format(Arrays.asList(results), fieldPositionFoundIndex);
+ ListFormatter.FormattedListBuilder builder = listFormatter.format(Arrays.asList(results),
+ fieldPositionFoundIndex);
// Fix up FieldPosition indexes if our field is found.
if (builder.getOffset() != -1) {
}
// type is one of "hm", "ms" or "hms"
- private static DateFormat loadNumericDurationFormat(
- ICUResourceBundle r, String type) {
+ private static DateFormat loadNumericDurationFormat(ICUResourceBundle r, String type) {
r = r.getWithFallback(String.format("durationUnits/%s", type));
// We replace 'h' with 'H' because 'h' does not make sense in the context of durations.
DateFormat result = new SimpleDateFormat(r.getString().replace("h", "H"));
}
// convert hours, minutes, seconds into milliseconds.
long millis = (long) (((Math.floor(hms[0].doubleValue()) * 60.0
- + Math.floor(hms[1].doubleValue())) * 60.0
- + Math.floor(hms[2].doubleValue())) * 1000.0);
+ + Math.floor(hms[1].doubleValue())) * 60.0 + Math.floor(hms[2].doubleValue())) * 1000.0);
Date d = new Date(millis);
// if hour-minute-second
if (startIndex == 0 && endIndex == 2) {
- return formatNumeric(
- d,
+ return formatNumeric(d,
numericFormatters.getHourMinuteSecond(),
DateFormat.Field.SECOND,
hms[endIndex],
}
// if minute-second
if (startIndex == 1 && endIndex == 2) {
- return formatNumeric(
- d,
+ return formatNumeric(d,
numericFormatters.getMinuteSecond(),
DateFormat.Field.SECOND,
hms[endIndex],
}
// if hour-minute
if (startIndex == 0 && endIndex == 1) {
- return formatNumeric(
- d,
+ return formatNumeric(d,
numericFormatters.getHourMinute(),
DateFormat.Field.MINUTE,
hms[endIndex],
// integer part with the corresponding value from formatting the date. Otherwise
// when formatting 0 minutes 9 seconds, we may get "00:9" instead of "00:09"
FieldPosition intFieldPosition = new FieldPosition(NumberFormat.INTEGER_FIELD);
- smallestAmountFormatted = numberFormat.format(
- smallestAmount, new StringBuffer(), intFieldPosition).toString();
+ smallestAmountFormatted = numberFormat
+ .format(smallestAmount, new StringBuffer(), intFieldPosition).toString();
// Give up if there is no integer field.
if (intFieldPosition.getBeginIndex() == 0 && intFieldPosition.getEndIndex() == 0) {
throw new IllegalStateException();
// Format our duration as a date, but keep track of where the smallest field is
// so that we can use it to replace the integer portion of the smallest value.
FieldPosition smallestFieldPosition = new FieldPosition(smallestField);
- String draft = formatter.format(
- duration, new StringBuffer(), smallestFieldPosition).toString();
+ String draft = formatter.format(duration, new StringBuffer(), smallestFieldPosition).toString();
// If we find the smallest field
- if (smallestFieldPosition.getBeginIndex() != 0
- || smallestFieldPosition.getEndIndex() != 0) {
+ if (smallestFieldPosition.getBeginIndex() != 0 || smallestFieldPosition.getEndIndex() != 0) {
// add everything up to the start of the smallest field in duration.
appendTo.append(draft, 0, smallestFieldPosition.getBeginIndex());
// Add the smallest field in formatted duration in lieu of the integer portion
// of smallest field
- appendTo.append(
- draft,
+ appendTo.append(draft,
smallestFieldPosition.getBeginIndex(),
smallestFieldPosition.getEndIndex());
// Add the rest of the smallest field
- appendTo.append(
- smallestAmountFormatted,
+ appendTo.append(smallestAmountFormatted,
intFieldPosition.getEndIndex(),
smallestAmountFormatted.length());
appendTo.append(draft, smallestFieldPosition.getEndIndex(), draft.length());
}
private Object writeReplace() throws ObjectStreamException {
- return new MeasureProxy(
- getLocale(), formatWidth, numberFormat.get(), MEASURE_FORMAT);
+ return new MeasureProxy(getLocale(), formatWidth, numberFormat.get(), MEASURE_FORMAT);
}
static class MeasureProxy implements Externalizable {
private int subClass;
private HashMap<Object, Object> keyValues;
- public MeasureProxy(
- ULocale locale,
- FormatWidth width,
- NumberFormat numberFormat,
- int subClass) {
+ public MeasureProxy(ULocale locale, FormatWidth width, NumberFormat numberFormat, int subClass) {
this.locale = locale;
this.formatWidth = width;
this.numberFormat = numberFormat;
return values[ordinal];
}
- private static final Map<ULocale, String> localeIdToRangeFormat =
- new ConcurrentHashMap<ULocale, String>();
+ private static final Map<ULocale, String> localeIdToRangeFormat = new ConcurrentHashMap<ULocale, String>();
/**
* Return a formatter (compiled SimpleFormatter pattern) for a range, such as "{0}–{1}".
- * @param forLocale locale to get the format for
- * @param width the format width
+ *
+ * @param forLocale
+ * locale to get the format for
+ * @param width
+ * the format width
* @return range formatter, such as "{0}–{1}"
* @internal
* @deprecated This API is ICU internal only.
}
String result = localeIdToRangeFormat.get(forLocale);
if (result == null) {
- ICUResourceBundle rb = (ICUResourceBundle)UResourceBundle.
- getBundleInstance(ICUData.ICU_BASE_NAME, forLocale);
+ ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle
+ .getBundleInstance(ICUData.ICU_BASE_NAME, forLocale);
ULocale realLocale = rb.getULocale();
- if (!forLocale.equals(realLocale)) { // if the child would inherit, then add a cache entry for it.
+ if (!forLocale.equals(realLocale)) { // if the child would inherit, then add a cache entry
+ // for it.
result = localeIdToRangeFormat.get(forLocale);
if (result != null) {
localeIdToRangeFormat.put(forLocale, result);
String resultString = null;
try {
- resultString = rb.getStringWithFallback("NumberElements/" + ns.getName() + "/miscPatterns/range");
- } catch ( MissingResourceException ex ) {
+ resultString = rb
+ .getStringWithFallback("NumberElements/" + ns.getName() + "/miscPatterns/range");
+ } catch (MissingResourceException ex) {
resultString = rb.getStringWithFallback("NumberElements/latn/patterns/range");
}
- result = SimpleFormatterImpl.compileToStringMinMaxArguments(
- resultString, new StringBuilder(), 2, 2);
+ result = SimpleFormatterImpl
+ .compileToStringMinMaxArguments(resultString, new StringBuilder(), 2, 2);
localeIdToRangeFormat.put(forLocale, result);
if (!forLocale.equals(realLocale)) {
localeIdToRangeFormat.put(realLocale, result);
import com.ibm.icu.util.ULocale.Category;
import com.ibm.icu.util.UResourceBundle;
-
/**
* Format or parse a TimeUnitAmount, using plural rules for the units where available.
*
* <P>
* Code Sample:
+ *
* <pre>
- * // create a time unit instance.
- * // only SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, and YEAR are supported
- * TimeUnit timeUnit = TimeUnit.SECOND;
- * // create time unit amount instance - a combination of Number and time unit
- * TimeUnitAmount source = new TimeUnitAmount(2, timeUnit);
- * // create time unit format instance
- * TimeUnitFormat format = new TimeUnitFormat();
- * // set the locale of time unit format
- * format.setLocale(new ULocale("en"));
- * // format a time unit amount
- * String formatted = format.format(source);
- * System.out.println(formatted);
- * try {
- * // parse a string into time unit amount
- * TimeUnitAmount result = (TimeUnitAmount) format.parseObject(formatted);
- * // result should equal to source
- * } catch (ParseException e) {
- * }
+ * // create a time unit instance.
+ * // only SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, and YEAR are supported
+ * TimeUnit timeUnit = TimeUnit.SECOND;
+ * // create time unit amount instance - a combination of Number and time unit
+ * TimeUnitAmount source = new TimeUnitAmount(2, timeUnit);
+ * // create time unit format instance
+ * TimeUnitFormat format = new TimeUnitFormat();
+ * // set the locale of time unit format
+ * format.setLocale(new ULocale("en"));
+ * // format a time unit amount
+ * String formatted = format.format(source);
+ * System.out.println(formatted);
+ * try {
+ * // parse a string into time unit amount
+ * TimeUnitAmount result = (TimeUnitAmount) format.parseObject(formatted);
+ * // result should equal to source
+ * } catch (ParseException e) {
+ * }
* </pre>
*
* <P>
+ *
* @see TimeUnitAmount
* @see MeasureFormat
* @author markdavis
public class TimeUnitFormat extends MeasureFormat {
/**
- * Constant for full name style format.
- * For example, the full name for "hour" in English is "hour" or "hours".
+ * Constant for full name style format. For example, the full name for "hour" in English is "hour" or
+ * "hours".
+ *
* @deprecated ICU 53 see {@link MeasureFormat.FormatWidth}
*/
@Deprecated
public static final int FULL_NAME = 0;
/**
- * Constant for abbreviated name style format.
- * For example, the abbreviated name for "hour" in English is "hr" or "hrs".
+ * Constant for abbreviated name style format. For example, the abbreviated name for "hour" in
+ * English is "hr" or "hrs".
+ *
* @deprecated ICU 53 see {@link MeasureFormat.FormatWidth}
*/
@Deprecated
private static final String DEFAULT_PATTERN_FOR_YEAR = "{0} y";
/**
- * Create empty format using full name style, for example, "hours".
- * Use setLocale and/or setFormat to modify.
+ * Create empty format using full name style, for example, "hours". Use setLocale and/or setFormat to
+ * modify.
+ *
* @deprecated ICU 53 use {@link MeasureFormat} instead.
*/
@Deprecated
/**
* Create TimeUnitFormat given a ULocale, and using full name style.
- * @param locale locale of this time unit formatter.
+ *
+ * @param locale
+ * locale of this time unit formatter.
* @deprecated ICU 53 use {@link MeasureFormat} instead.
*/
@Deprecated
/**
* Create TimeUnitFormat given a Locale, and using full name style.
- * @param locale locale of this time unit formatter.
+ *
+ * @param locale
+ * locale of this time unit formatter.
* @deprecated ICU 53 use {@link MeasureFormat} instead.
*/
@Deprecated
/**
* Create TimeUnitFormat given a ULocale and a formatting style.
- * @param locale locale of this time unit formatter.
- * @param style format style, either FULL_NAME or ABBREVIATED_NAME style.
- * @throws IllegalArgumentException if the style is not FULL_NAME or
- * ABBREVIATED_NAME style.
+ *
+ * @param locale
+ * locale of this time unit formatter.
+ * @param style
+ * format style, either FULL_NAME or ABBREVIATED_NAME style.
+ * @throws IllegalArgumentException
+ * if the style is not FULL_NAME or ABBREVIATED_NAME style.
* @deprecated ICU 53 use {@link MeasureFormat} instead.
*/
@Deprecated
public TimeUnitFormat(ULocale locale, int style) {
if (style < FULL_NAME || style >= TOTAL_STYLES) {
- throw new IllegalArgumentException("style should be either FULL_NAME or ABBREVIATED_NAME style");
+ throw new IllegalArgumentException(
+ "style should be either FULL_NAME or ABBREVIATED_NAME style");
}
- mf = MeasureFormat.getInstance(
- locale, style == FULL_NAME ? FormatWidth.WIDE : FormatWidth.SHORT);
+ mf = MeasureFormat.getInstance(locale,
+ style == FULL_NAME ? FormatWidth.WIDE : FormatWidth.SHORT);
this.style = style;
// Needed for getLocale(ULocale.VALID_LOCALE)
/**
* Create TimeUnitFormat given a Locale and a formatting style.
+ *
* @deprecated ICU 53 use {@link MeasureFormat} instead.
*/
@Deprecated
public TimeUnitFormat(Locale locale, int style) {
- this(ULocale.forLocale(locale), style);
+ this(ULocale.forLocale(locale), style);
}
/**
* Set the locale used for formatting or parsing.
- * @param locale locale of this time unit formatter.
+ *
+ * @param locale
+ * locale of this time unit formatter.
* @return this, for chaining.
* @deprecated ICU 53 see {@link MeasureFormat}.
*/
@Deprecated
public TimeUnitFormat setLocale(ULocale locale) {
- if (locale != this.locale){
+ if (locale != this.locale) {
mf = mf.withLocale(locale);
// Needed for getLocale(ULocale.VALID_LOCALE)
/**
* Set the locale used for formatting or parsing.
- * @param locale locale of this time unit formatter.
+ *
+ * @param locale
+ * locale of this time unit formatter.
* @return this, for chaining.
* @deprecated ICU 53 see {@link MeasureFormat}.
*/
/**
* Set the format used for formatting or parsing. Passing null is equivalent to passing
* {@link NumberFormat#getNumberInstance(ULocale)}.
- * @param format the number formatter.
+ *
+ * @param format
+ * the number formatter.
* @return this, for chaining.
* @deprecated ICU 53 see {@link MeasureFormat}.
*/
return this;
}
-
/**
* Format a TimeUnitAmount.
+ *
* @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
* @deprecated ICU 53 see {@link MeasureFormat}.
*/
+ @Override
@Deprecated
- public StringBuffer format(Object obj, StringBuffer toAppendTo,
- FieldPosition pos) {
+ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return mf.format(obj, toAppendTo, pos);
}
/**
* Parse a TimeUnitAmount.
+ *
* @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition)
* @deprecated ICU 53 see {@link MeasureFormat}.
*/
if (tempObj instanceof Number) {
temp = (Number) tempObj;
} else {
- // Since we now format the number ourselves, parseObject will likely give us back a String
+ // Since we now format the number ourselves, parseObject will likely give us
+ // back a String
// for
- // the number. When this happens we must parse the formatted number ourselves.
+ // the number. When this happens we must parse the formatted number
+ // ourselves.
try {
temp = format.parse(tempObj.toString());
} catch (ParseException e) {
}
}
/*
- * After find the longest match, parse the number. Result number could be null for the pattern without number
- * pattern. such as unit pattern in Arabic. When result number is null, use plural rule to set the number.
+ * After find the longest match, parse the number. Result number could be null for the pattern
+ * without number pattern. such as unit pattern in Arabic. When result number is null, use plural
+ * rule to set the number.
*/
if (resultNumber == null && longestParseDistance != 0) {
// set the number using plurrual count
ULocale locale;
boolean beenHere;
- TimeUnitFormatSetupSink(Map<TimeUnit, Map<String, Object[]>> timeUnitToCountToPatterns,
- int style, Set<String> pluralKeywords, ULocale locale) {
+ TimeUnitFormatSetupSink(
+ Map<TimeUnit, Map<String, Object[]>> timeUnitToCountToPatterns,
+ int style,
+ Set<String> pluralKeywords,
+ ULocale locale) {
this.timeUnitToCountToPatterns = timeUnitToCountToPatterns;
this.style = style;
this.pluralKeywords = pluralKeywords;
} else {
beenHere = true;
}
-
+
UResource.Table units = value.getTable();
for (int i = 0; units.getKeyAndValue(i, key, value); ++i) {
String timeUnitName = key.toString();
}
}
- private void setup(String resourceKey, Map<TimeUnit, Map<String, Object[]>> timeUnitToCountToPatterns, int style,
+ private void setup(
+ String resourceKey,
+ Map<TimeUnit, Map<String, Object[]>> timeUnitToCountToPatterns,
+ int style,
Set<String> pluralKeywords) {
// fill timeUnitToCountToPatterns from resource file
try {
- ICUResourceBundle resource = (ICUResourceBundle) UResourceBundle.getBundleInstance(
- ICUData.ICU_UNIT_BASE_NAME, locale);
+ ICUResourceBundle resource = (ICUResourceBundle) UResourceBundle
+ .getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, locale);
- TimeUnitFormatSetupSink sink = new TimeUnitFormatSetupSink(
- timeUnitToCountToPatterns, style, pluralKeywords, locale);
+ TimeUnitFormatSetupSink sink = new TimeUnitFormatSetupSink(timeUnitToCountToPatterns,
+ style,
+ pluralKeywords,
+ locale);
resource.getAllItemsWithFallback(resourceKey, sink);
} catch (MissingResourceException e) {
}
timeUnitToCountToPatterns.put(timeUnit, countToPatterns);
}
for (String pluralCount : keywords) {
- if (countToPatterns.get(pluralCount) == null || countToPatterns.get(pluralCount)[style] == null) {
+ if (countToPatterns.get(pluralCount) == null
+ || countToPatterns.get(pluralCount)[style] == null) {
// look through parents
- searchInTree(resourceKey, style, timeUnit, pluralCount, pluralCount, countToPatterns);
+ searchInTree(resourceKey,
+ style,
+ timeUnit,
+ pluralCount,
+ pluralCount,
+ countToPatterns);
}
}
}
// if the pattern is not found even in root, fallback to
// using patterns of plural count "other",
// then, "other" is the searchPluralCount.
- private void searchInTree(String resourceKey, int styl, TimeUnit timeUnit, String srcPluralCount,
- String searchPluralCount, Map<String, Object[]> countToPatterns) {
+ private void searchInTree(
+ String resourceKey,
+ int styl,
+ TimeUnit timeUnit,
+ String srcPluralCount,
+ String searchPluralCount,
+ Map<String, Object[]> countToPatterns) {
ULocale parentLocale = locale;
String srcTimeUnitName = timeUnit.toString();
while (parentLocale != null) {
try {
// look for pattern for srcPluralCount in locale tree
- ICUResourceBundle unitsRes = (ICUResourceBundle) UResourceBundle.getBundleInstance(
- ICUData.ICU_UNIT_BASE_NAME, parentLocale);
+ ICUResourceBundle unitsRes = (ICUResourceBundle) UResourceBundle
+ .getBundleInstance(ICUData.ICU_UNIT_BASE_NAME, parentLocale);
unitsRes = unitsRes.getWithFallback(resourceKey);
ICUResourceBundle oneUnitRes = unitsRes.getWithFallback(srcTimeUnitName);
String pattern = oneUnitRes.getStringWithFallback(searchPluralCount);
// boilerplate code to make TimeUnitFormat otherwise follow the contract of
// MeasureFormat
-
/**
* @internal
* @deprecated This API is ICU internal only.
@Deprecated
@Override
public StringBuilder formatMeasures(
- StringBuilder appendTo, FieldPosition fieldPosition, Measure... measures) {
+ StringBuilder appendTo,
+ FieldPosition fieldPosition,
+ Measure... measures) {
return mf.formatMeasures(appendTo, fieldPosition, measures);
}