下面列出了java.text.FieldPosition#getBeginIndex ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Formats the pattern with the value and adjusts the FieldPosition.
*/
public static StringBuilder format(String compiledPattern, CharSequence value,
StringBuilder appendTo, FieldPosition pos) {
int[] offsets = new int[1];
SimpleFormatterImpl.formatAndAppend(compiledPattern, appendTo, offsets, value);
if (pos.getBeginIndex() != 0 || pos.getEndIndex() != 0) {
if (offsets[0] >= 0) {
pos.setBeginIndex(pos.getBeginIndex() + offsets[0]);
pos.setEndIndex(pos.getEndIndex() + offsets[0]);
} else {
pos.setBeginIndex(0);
pos.setEndIndex(0);
}
}
return appendTo;
}
/**
* Formats a single measure per unit.
*
* 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.
* @return appendTo.
* @stable ICU 55
*/
public StringBuilder formatMeasurePerUnit(
Measure measure,
MeasureUnit perUnit,
StringBuilder appendTo,
FieldPosition pos) {
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());
int offset = withPerUnitAndAppend(
formatMeasure(measure, numberFormat, new StringBuilder(), fpos),
perUnit,
appendTo);
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
pos.setBeginIndex(fpos.getBeginIndex() + offset);
pos.setEndIndex(fpos.getEndIndex() + offset);
}
return appendTo;
}
/**
* Formats the pattern with the value and adjusts the FieldPosition.
*/
public static StringBuilder format(String compiledPattern, CharSequence value,
StringBuilder appendTo, FieldPosition pos) {
int[] offsets = new int[1];
SimpleFormatterImpl.formatAndAppend(compiledPattern, appendTo, offsets, value);
if (pos.getBeginIndex() != 0 || pos.getEndIndex() != 0) {
if (offsets[0] >= 0) {
pos.setBeginIndex(pos.getBeginIndex() + offsets[0]);
pos.setEndIndex(pos.getEndIndex() + offsets[0]);
} else {
pos.setBeginIndex(0);
pos.setEndIndex(0);
}
}
return appendTo;
}
/**
* Formats a single measure per unit.
*
* 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.
* @return appendTo.
*/
public StringBuilder formatMeasurePerUnit(
Measure measure,
MeasureUnit perUnit,
StringBuilder appendTo,
FieldPosition pos) {
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());
int offset = withPerUnitAndAppend(
formatMeasure(measure, numberFormat, new StringBuilder(), fpos),
perUnit,
appendTo);
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
pos.setBeginIndex(fpos.getBeginIndex() + offset);
pos.setEndIndex(fpos.getEndIndex() + offset);
}
return appendTo;
}
/**
* API tests for API addition request A23. FieldPosition.getBeginIndex and
* FieldPosition.getEndIndex.
*/
@Test
public void Test4062486()
{
DecimalFormat fmt = new DecimalFormat("#,##0.00");
StringBuffer formatted = new StringBuffer();
FieldPosition field = new FieldPosition(0);
Double num = new Double(1234.5);
fmt.format(num, formatted, field);
if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)
errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
field.setBeginIndex(7);
field.setEndIndex(4);
if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)
errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
}
protected void t_FormatWithField(int count, Format format, Object object,
String text, Format.Field field, int begin, int end) {
StringBuffer buffer = new StringBuffer();
FieldPosition pos = new FieldPosition(field);
format.format(object, buffer, pos);
// System.out.println(buffer);
// System.out.println(pos);
if (text == null) {
assertEquals("Test " + count + ": incorrect formatted text", this.text, buffer.toString());
} else {
assertEquals(text, buffer.toString());
}
if (begin != pos.getBeginIndex() || end != pos.getEndIndex()) {
assertEquals(field + " " + begin + ".." + end,
pos.getFieldAttribute() + " " + pos.getBeginIndex() + ".." + pos.getEndIndex());
}
}
@SuppressWarnings("deprecation")
com.ibm.icu.text.PluralRules.FixedDecimal toFixedDecimal(double n) {
NumberFormat nf = getNumberFormat();
StringBuffer sb = new StringBuffer();
FieldPosition fp = new FieldPosition(DecimalFormat.FRACTION_FIELD);
nf.format(n, sb, fp);
int v = fp.getEndIndex() - fp.getBeginIndex();
long f = 0;
if (v > 0) {
ParsePosition pp = new ParsePosition(fp.getBeginIndex());
f = nf.parse(sb.toString(), pp).longValue();
}
return new com.ibm.icu.text.PluralRules.FixedDecimal(n, v, f);
}
/**
* 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.
*
* @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());
if (obj instanceof Collection) {
Collection<?> coll = (Collection<?>) obj;
Measure[] measures = new Measure[coll.size()];
int idx = 0;
for (Object o : coll) {
if (!(o instanceof Measure)) {
throw new IllegalArgumentException(obj.toString());
}
measures[idx++] = (Measure) o;
}
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){
toAppendTo.append(formatMeasure((Measure) obj, numberFormat, new StringBuilder(), fpos));
} else {
throw new IllegalArgumentException(obj.toString());
}
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
pos.setBeginIndex(fpos.getBeginIndex() + prevLength);
pos.setEndIndex(fpos.getEndIndex() + prevLength);
}
return toAppendTo;
}
private StringBuilder formatMeasuresSlowTrack(
ListFormatter listFormatter,
StringBuilder appendTo,
FieldPosition fieldPosition,
Measure... measures) {
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());
int fieldPositionFoundIndex = -1;
for (int i = 0; i < measures.length; ++i) {
ImmutableNumberFormat nf = (i == measures.length - 1 ? numberFormat : integerFormat);
if (fieldPositionFoundIndex == -1) {
results[i] = formatMeasure(measures[i], nf, new StringBuilder(), fpos).toString();
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
fieldPositionFoundIndex = i;
}
} else {
results[i] = formatMeasure(measures[i], nf);
}
}
ListFormatter.FormattedListBuilder builder =
listFormatter.format(Arrays.asList(results), fieldPositionFoundIndex);
// Fix up FieldPosition indexes if our field is found.
if (builder.getOffset() != -1) {
fieldPosition.setBeginIndex(fpos.getBeginIndex() + builder.getOffset() + appendTo.length());
fieldPosition.setEndIndex(fpos.getEndIndex() + builder.getOffset() + appendTo.length());
}
return appendTo.append(builder.toString());
}
/**
* Searches a string for another string. If lenient parsing is off,
* this just calls indexOf(). If lenient parsing is on, this function
* uses CollationElementIterator to match characters, and only
* primary-order differences are significant in determining whether
* there's a match.
* @param str The string to search
* @param key The string to search "str" for
* @param startingAt The index into "str" where the search is to
* begin
* @return A two-element array of ints. Element 0 is the position
* of the match, or -1 if there was no match. Element 1 is the
* number of characters in "str" that matched (which isn't necessarily
* the same as the length of "key")
*/
private int[] findText(String str, String key, PluralFormat pluralFormatKey, int startingAt) {
RbnfLenientScanner scanner = formatter.getLenientScanner();
if (pluralFormatKey != null) {
FieldPosition position = new FieldPosition(NumberFormat.INTEGER_FIELD);
position.setBeginIndex(startingAt);
pluralFormatKey.parseType(str, scanner, position);
int start = position.getBeginIndex();
if (start >= 0) {
int pluralRuleStart = ruleText.indexOf("$(");
int pluralRuleSuffix = ruleText.indexOf(")$", pluralRuleStart) + 2;
int matchLen = position.getEndIndex() - start;
String prefix = ruleText.substring(0, pluralRuleStart);
String suffix = ruleText.substring(pluralRuleSuffix);
if (str.regionMatches(start - prefix.length(), prefix, 0, prefix.length())
&& str.regionMatches(start + matchLen, suffix, 0, suffix.length()))
{
return new int[]{start - prefix.length(), matchLen + prefix.length() + suffix.length()};
}
}
return new int[]{-1, 0};
}
if (scanner != null) {
// if lenient parsing is turned ON, we've got some work
// ahead of us
return scanner.findText(str, key, startingAt);
}
// if lenient parsing is turned off, this is easy. Just call
// String.indexOf() and we're done
return new int[]{str.indexOf(key, startingAt), key.length()};
}
/**
* 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.
*
* @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)
*/
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
int prevLength = toAppendTo.length();
FieldPosition fpos =
new FieldPosition(pos.getFieldAttribute(), pos.getField());
if (obj instanceof Collection) {
Collection<?> coll = (Collection<?>) obj;
Measure[] measures = new Measure[coll.size()];
int idx = 0;
for (Object o : coll) {
if (!(o instanceof Measure)) {
throw new IllegalArgumentException(obj.toString());
}
measures[idx++] = (Measure) o;
}
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){
toAppendTo.append(formatMeasure((Measure) obj, numberFormat, new StringBuilder(), fpos));
} else {
throw new IllegalArgumentException(obj.toString());
}
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
pos.setBeginIndex(fpos.getBeginIndex() + prevLength);
pos.setEndIndex(fpos.getEndIndex() + prevLength);
}
return toAppendTo;
}
private StringBuilder formatMeasuresSlowTrack(
ListFormatter listFormatter,
StringBuilder appendTo,
FieldPosition fieldPosition,
Measure... measures) {
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());
int fieldPositionFoundIndex = -1;
for (int i = 0; i < measures.length; ++i) {
ImmutableNumberFormat nf = (i == measures.length - 1 ? numberFormat : integerFormat);
if (fieldPositionFoundIndex == -1) {
results[i] = formatMeasure(measures[i], nf, new StringBuilder(), fpos).toString();
if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
fieldPositionFoundIndex = i;
}
} else {
results[i] = formatMeasure(measures[i], nf);
}
}
ListFormatter.FormattedListBuilder builder =
listFormatter.format(Arrays.asList(results), fieldPositionFoundIndex);
// Fix up FieldPosition indexes if our field is found.
if (builder.getOffset() != -1) {
fieldPosition.setBeginIndex(fpos.getBeginIndex() + builder.getOffset() + appendTo.length());
fieldPosition.setEndIndex(fpos.getEndIndex() + builder.getOffset() + appendTo.length());
}
return appendTo.append(builder.toString());
}
/**
* Searches a string for another string. If lenient parsing is off,
* this just calls indexOf(). If lenient parsing is on, this function
* uses CollationElementIterator to match characters, and only
* primary-order differences are significant in determining whether
* there's a match.
* @param str The string to search
* @param key The string to search "str" for
* @param startingAt The index into "str" where the search is to
* begin
* @return A two-element array of ints. Element 0 is the position
* of the match, or -1 if there was no match. Element 1 is the
* number of characters in "str" that matched (which isn't necessarily
* the same as the length of "key")
*/
private int[] findText(String str, String key, PluralFormat pluralFormatKey, int startingAt) {
RbnfLenientScanner scanner = formatter.getLenientScanner();
if (pluralFormatKey != null) {
FieldPosition position = new FieldPosition(NumberFormat.INTEGER_FIELD);
position.setBeginIndex(startingAt);
pluralFormatKey.parseType(str, scanner, position);
int start = position.getBeginIndex();
if (start >= 0) {
int pluralRuleStart = ruleText.indexOf("$(");
int pluralRuleSuffix = ruleText.indexOf(")$", pluralRuleStart) + 2;
int matchLen = position.getEndIndex() - start;
String prefix = ruleText.substring(0, pluralRuleStart);
String suffix = ruleText.substring(pluralRuleSuffix);
if (str.regionMatches(start - prefix.length(), prefix, 0, prefix.length())
&& str.regionMatches(start + matchLen, suffix, 0, suffix.length()))
{
return new int[]{start - prefix.length(), matchLen + prefix.length() + suffix.length()};
}
}
return new int[]{-1, 0};
}
if (scanner != null) {
// if lenient parsing is turned ON, we've got some work
// ahead of us
return scanner.findText(str, key, startingAt);
}
// if lenient parsing is turned off, this is easy. Just call
// String.indexOf() and we're done
return new int[]{str.indexOf(key, startingAt), key.length()};
}
/**
* @bug 4101483
*/
@Test
public void Test4101483() {
SimpleDateFormat sdf = new SimpleDateFormat("z", Locale.US);
FieldPosition fp = new FieldPosition(DateFormat.TIMEZONE_FIELD);
Date d = new Date(9234567890L);
StringBuffer buf = new StringBuffer("");
sdf.format(d, buf, fp);
logln(sdf.format(d, buf, fp).toString());
logln("beginIndex = " + fp.getBeginIndex());
logln("endIndex = " + fp.getEndIndex());
if (fp.getBeginIndex() == fp.getEndIndex())
errln("Fail: Empty field");
}
private StringBuilder formatNumeric(
Date duration,
DateFormat formatter,
DateFormat.Field smallestField,
Number smallestAmount,
StringBuilder appendTo) {
// Format the smallest amount ahead of time.
String smallestAmountFormatted;
// Format the smallest amount using this object's number format, but keep track
// of the integer portion of this formatted amount. We have to replace just the
// 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();
// 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();
// If we find the smallest field
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 everything in the smallest field up to the integer portion
appendTo.append(smallestAmountFormatted, 0, intFieldPosition.getBeginIndex());
// Add the smallest field in formatted duration in lieu of the integer portion
// of smallest field
appendTo.append(
draft,
smallestFieldPosition.getBeginIndex(),
smallestFieldPosition.getEndIndex());
// Add the rest of the smallest field
appendTo.append(
smallestAmountFormatted,
intFieldPosition.getEndIndex(),
smallestAmountFormatted.length());
appendTo.append(draft, smallestFieldPosition.getEndIndex(), draft.length());
} else {
// As fallback, just use the formatted duration.
appendTo.append(draft);
}
return appendTo;
}
/**
* This method returns the PluralRules type found from parsing.
* @param source the string to be parsed.
* @param pos defines the position where parsing is to begin,
* and upon return, the position where parsing left off. If the position
* is a negative index, then parsing failed.
* @return Returns the PluralRules type. For example, it could be "zero", "one", "two", "few", "many" or "other")
*/
/*package*/ String parseType(String source, RbnfLenientScanner scanner, FieldPosition pos) {
// If no pattern was applied, return null.
if (msgPattern == null || msgPattern.countParts() == 0) {
pos.setBeginIndex(-1);
pos.setEndIndex(-1);
return null;
}
int partIndex = 0;
int currMatchIndex;
int count=msgPattern.countParts();
int startingAt = pos.getBeginIndex();
if (startingAt < 0) {
startingAt = 0;
}
// The keyword is null until we need to match against a non-explicit, not-"other" value.
// Then we get the keyword from the selector.
// (In other words, we never call the selector if we match against an explicit value,
// or if the only non-explicit keyword is "other".)
String keyword = null;
String matchedWord = null;
int matchedIndex = -1;
// Iterate over (ARG_SELECTOR ARG_START message ARG_LIMIT) tuples
// until the end of the plural-only pattern.
while (partIndex < count) {
MessagePattern.Part partSelector=msgPattern.getPart(partIndex++);
if (partSelector.getType() != MessagePattern.Part.Type.ARG_SELECTOR) {
// Bad format
continue;
}
MessagePattern.Part partStart=msgPattern.getPart(partIndex++);
if (partStart.getType() != MessagePattern.Part.Type.MSG_START) {
// Bad format
continue;
}
MessagePattern.Part partLimit=msgPattern.getPart(partIndex++);
if (partLimit.getType() != MessagePattern.Part.Type.MSG_LIMIT) {
// Bad format
continue;
}
String currArg = pattern.substring(partStart.getLimit(), partLimit.getIndex());
if (scanner != null) {
// If lenient parsing is turned ON, we've got some time consuming parsing ahead of us.
int[] scannerMatchResult = scanner.findText(source, currArg, startingAt);
currMatchIndex = scannerMatchResult[0];
}
else {
currMatchIndex = source.indexOf(currArg, startingAt);
}
if (currMatchIndex >= 0 && currMatchIndex >= matchedIndex && (matchedWord == null || currArg.length() > matchedWord.length())) {
matchedIndex = currMatchIndex;
matchedWord = currArg;
keyword = pattern.substring(partStart.getLimit(), partLimit.getIndex());
}
}
if (keyword != null) {
pos.setBeginIndex(matchedIndex);
pos.setEndIndex(matchedIndex + matchedWord.length());
return keyword;
}
// Not found!
pos.setBeginIndex(-1);
pos.setEndIndex(-1);
return null;
}
private StringBuilder formatNumeric(
Date duration,
DateFormat formatter,
DateFormat.Field smallestField,
Number smallestAmount,
StringBuilder appendTo) {
// Format the smallest amount ahead of time.
String smallestAmountFormatted;
// Format the smallest amount using this object's number format, but keep track
// of the integer portion of this formatted amount. We have to replace just the
// 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();
// 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();
// If we find the smallest field
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 everything in the smallest field up to the integer portion
appendTo.append(smallestAmountFormatted, 0, intFieldPosition.getBeginIndex());
// Add the smallest field in formatted duration in lieu of the integer portion
// of smallest field
appendTo.append(
draft,
smallestFieldPosition.getBeginIndex(),
smallestFieldPosition.getEndIndex());
// Add the rest of the smallest field
appendTo.append(
smallestAmountFormatted,
intFieldPosition.getEndIndex(),
smallestAmountFormatted.length());
appendTo.append(draft, smallestFieldPosition.getEndIndex(), draft.length());
} else {
// As fallback, just use the formatted duration.
appendTo.append(draft);
}
return appendTo;
}
/**
* This method returns the PluralRules type found from parsing.
* @param source the string to be parsed.
* @param pos defines the position where parsing is to begin,
* and upon return, the position where parsing left off. If the position
* is a negative index, then parsing failed.
* @return Returns the PluralRules type. For example, it could be "zero", "one", "two", "few", "many" or "other")
*/
/*package*/ String parseType(String source, RbnfLenientScanner scanner, FieldPosition pos) {
// If no pattern was applied, return null.
if (msgPattern == null || msgPattern.countParts() == 0) {
pos.setBeginIndex(-1);
pos.setEndIndex(-1);
return null;
}
int partIndex = 0;
int currMatchIndex;
int count=msgPattern.countParts();
int startingAt = pos.getBeginIndex();
if (startingAt < 0) {
startingAt = 0;
}
// The keyword is null until we need to match against a non-explicit, not-"other" value.
// Then we get the keyword from the selector.
// (In other words, we never call the selector if we match against an explicit value,
// or if the only non-explicit keyword is "other".)
String keyword = null;
String matchedWord = null;
int matchedIndex = -1;
// Iterate over (ARG_SELECTOR ARG_START message ARG_LIMIT) tuples
// until the end of the plural-only pattern.
while (partIndex < count) {
MessagePattern.Part partSelector=msgPattern.getPart(partIndex++);
if (partSelector.getType() != MessagePattern.Part.Type.ARG_SELECTOR) {
// Bad format
continue;
}
MessagePattern.Part partStart=msgPattern.getPart(partIndex++);
if (partStart.getType() != MessagePattern.Part.Type.MSG_START) {
// Bad format
continue;
}
MessagePattern.Part partLimit=msgPattern.getPart(partIndex++);
if (partLimit.getType() != MessagePattern.Part.Type.MSG_LIMIT) {
// Bad format
continue;
}
String currArg = pattern.substring(partStart.getLimit(), partLimit.getIndex());
if (scanner != null) {
// If lenient parsing is turned ON, we've got some time consuming parsing ahead of us.
int[] scannerMatchResult = scanner.findText(source, currArg, startingAt);
currMatchIndex = scannerMatchResult[0];
}
else {
currMatchIndex = source.indexOf(currArg, startingAt);
}
if (currMatchIndex >= 0 && currMatchIndex >= matchedIndex && (matchedWord == null || currArg.length() > matchedWord.length())) {
matchedIndex = currMatchIndex;
matchedWord = currArg;
keyword = pattern.substring(partStart.getLimit(), partLimit.getIndex());
}
}
if (keyword != null) {
pos.setBeginIndex(matchedIndex);
pos.setEndIndex(matchedIndex + matchedWord.length());
return keyword;
}
// Not found!
pos.setBeginIndex(-1);
pos.setEndIndex(-1);
return null;
}
public String format( Date date )
{
StringBuffer str = new StringBuffer( );
FieldPosition pos = new FieldPosition( DateFormat.DATE_FIELD );
DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM, locale );
if ( tz != null )
{
df.setTimeZone( tz );
}
df.format( date, str, pos );
int endIndex;
if ( pos.getEndIndex( ) >= str.length( ) )
{
endIndex = pos.getEndIndex( );
}
else
{
endIndex = pos.getEndIndex( )
+ ( str.charAt( pos.getEndIndex( ) ) == ',' ? 2 : 1 );
}
if ( endIndex >= str.length( ) ) // means date is the last one, need
// to remove separator
{
endIndex = pos.getBeginIndex( );
while ( endIndex > 0 )
{
char ch = str.charAt( endIndex - 1 );
if ( ch == ' '
|| ch == ',' || ch == '/' || ch == '-' || ch == '.' )
{
endIndex--;
}
else
{
break;
}
}
return str.substring( 0, endIndex );
}
return str.substring( 0, pos.getBeginIndex( ) )
+ str.substring( endIndex );
}
/**
* Sets the value domain to the string representation of the given range.
*
* @param range the range to format.
* @param format the format to use for formatting the {@code range}.
* @param buffer a temporary buffer to use for formatting the range.
* @return the position of a character on which to align the text in the cell.
*/
final int setValueDomain(final Range<?> range, final Format format, final StringBuffer buffer) {
final FieldPosition fieldPosition = new FieldPosition(RangeFormat.Field.MAX_VALUE);
valueDomain = format.format(range, buffer, fieldPosition).toString();
buffer.setLength(0);
return valueDomainAlignment = fieldPosition.getBeginIndex();
}