下面列出了javax.validation.constraints.AssertTrue#java.text.ParsePosition 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void test_reducedWithLateChronoChangeTwice() {
DateTimeFormatter df
= new DateTimeFormatterBuilder()
.appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
.appendLiteral(" ")
.appendChronologyId()
.appendLiteral(" ")
.appendChronologyId()
.toFormatter();
int expected = 2044;
String input = "44 ThaiBuddhist ISO";
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = df.parseUnresolved(input, pos);
assertEquals(pos.getIndex(), input.length(), "Input not parsed completely: " + pos);
assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)");
int actual = parsed.get(YEAR);
assertEquals(actual, expected,
String.format("Wrong date parsed, chrono: %s, input: %s",
parsed.query(TemporalQueries.chronology()), input));
}
public String parseReference(String text, ParsePosition pos, int limit) {
int start = pos.getIndex();
int i = start;
String result = "";
while (i < limit) {
int c = UTF16.charAt(text, i);
if ((i == start && !UCharacter.isUnicodeIdentifierStart(c))
|| !UCharacter.isUnicodeIdentifierPart(c)) {
break;
}
i += UTF16.getCharCount(c);
}
if (i == start) { // No valid name chars
return result; // Indicate failure with empty string
}
pos.setIndex(i);
result = text.substring(start, i);
return result;
}
@Test(dataProvider="LocalWeekBasedYearPatterns")
public void test_parse_WeekBasedYear(String pattern, String text, int pos, int expectedPos, LocalDate expectedValue) {
ParsePosition ppos = new ParsePosition(pos);
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern);
DateTimeFormatter dtf = b.toFormatter(locale);
TemporalAccessor parsed = dtf.parseUnresolved(text, ppos);
if (ppos.getErrorIndex() != -1) {
assertEquals(ppos.getErrorIndex(), expectedPos);
} else {
WeekFields weekDef = WeekFields.of(locale);
assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position");
assertEquals(parsed.isSupported(weekDef.dayOfWeek()), pattern.indexOf('e') >= 0);
assertEquals(parsed.isSupported(weekDef.weekOfWeekBasedYear()), pattern.indexOf('w') >= 0);
assertEquals(parsed.isSupported(weekDef.weekBasedYear()), pattern.indexOf('Y') >= 0);
// ensure combination resolves into a date
LocalDate result = LocalDate.parse(text, dtf);
assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern + ", weekDef: " + weekDef);
}
}
/**
* Match text with the prefix tree.
*
* @param text the input text to parse, not null
* @param pos the position to start parsing at, from 0 to the text
* length. Upon return, position will be updated to the new parse
* position, or unchanged, if no match found.
* @return the resulting string, or null if no match found.
*/
public String match(CharSequence text, ParsePosition pos) {
int off = pos.getIndex();
int end = text.length();
if (!prefixOf(text, off, end)){
return null;
}
off += key.length();
if (child != null && off != end) {
PrefixTree c = child;
do {
if (isEqual(c.c0, text.charAt(off))) {
pos.setIndex(off);
String found = c.match(text, pos);
if (found != null) {
return found;
}
break;
}
c = c.sibling;
} while (c != null);
}
pos.setIndex(off);
return value;
}
/**
* Parse the format component of a format element.
*
* @param pattern string to parse
* @param pos current parse position
* @return Format description String
*/
private String parseFormatDescription(String pattern, ParsePosition pos) {
int start = pos.getIndex();
seekNonWs(pattern, pos);
int text = pos.getIndex();
int depth = 1;
for (; pos.getIndex() < pattern.length(); next(pos)) {
switch (pattern.charAt(pos.getIndex())) {
case START_FE:
depth++;
break;
case END_FE:
depth--;
if (depth == 0) {
return pattern.substring(text, pos.getIndex());
}
break;
case QUOTE:
getQuotedString(pattern, pos, false);
break;
}
}
throw new IllegalArgumentException(
"Unterminated format element at position " + start);
}
/**
* Parses and resolves the specified text.
* <p>
* This parses to a {@code TemporalAccessor} ensuring that the text is fully parsed.
*
* @param text the text to parse, not null
* @param position the position to parse from, updated with length parsed
* and the index of any error, null if parsing whole string
* @return the resolved result of the parse, not null
* @throws DateTimeParseException if the parse fails
* @throws DateTimeException if an error occurs while resolving the date or time
* @throws IndexOutOfBoundsException if the position is invalid
*/
private TemporalAccessor parseResolved0(final CharSequence text, final ParsePosition position) {
ParsePosition pos = (position != null ? position : new ParsePosition(0));
DateTimeParseContext context = parseUnresolved0(text, pos);
if (context == null || pos.getErrorIndex() >= 0 || (position == null && pos.getIndex() < text.length())) {
String abbr;
if (text.length() > 64) {
abbr = text.subSequence(0, 64).toString() + "...";
} else {
abbr = text.toString();
}
if (pos.getErrorIndex() >= 0) {
throw new DateTimeParseException("Text '" + abbr + "' could not be parsed at index " +
pos.getErrorIndex(), text, pos.getErrorIndex());
} else {
throw new DateTimeParseException("Text '" + abbr + "' could not be parsed, unparsed text found at index " +
pos.getIndex(), text, pos.getIndex());
}
}
return context.toResolved(resolverStyle, resolverFields);
}
@Test(dataProvider="LocalWeekBasedYearPatterns")
public void test_parse_WeekBasedYear(String pattern, String text, int pos, int expectedPos, LocalDate expectedValue) {
ParsePosition ppos = new ParsePosition(pos);
DateTimeFormatterBuilder b = new DateTimeFormatterBuilder().appendPattern(pattern);
DateTimeFormatter dtf = b.toFormatter(locale);
TemporalAccessor parsed = dtf.parseUnresolved(text, ppos);
if (ppos.getErrorIndex() != -1) {
assertEquals(ppos.getErrorIndex(), expectedPos);
} else {
WeekFields weekDef = WeekFields.of(locale);
assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position");
assertEquals(parsed.isSupported(weekDef.dayOfWeek()), pattern.indexOf('e') >= 0);
assertEquals(parsed.isSupported(weekDef.weekOfWeekBasedYear()), pattern.indexOf('w') >= 0);
assertEquals(parsed.isSupported(weekDef.weekBasedYear()), pattern.indexOf('Y') >= 0);
// ensure combination resolves into a date
LocalDate result = LocalDate.parse(text, dtf);
assertEquals(result, expectedValue, "LocalDate incorrect for " + pattern + ", weekDef: " + weekDef);
}
}
@Test
public void test_reducedWithLateChronoChangeTwice() {
DateTimeFormatter df
= new DateTimeFormatterBuilder()
.appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
.appendLiteral(" ")
.appendChronologyId()
.appendLiteral(" ")
.appendChronologyId()
.toFormatter();
int expected = 2044;
String input = "44 ThaiBuddhist ISO";
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = df.parseUnresolved(input, pos);
assertEquals(pos.getIndex(), input.length(), "Input not parsed completely: " + pos);
assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)");
int actual = parsed.get(YEAR);
assertEquals(actual, expected,
String.format("Wrong date parsed, chrono: %s, input: %s",
parsed.query(TemporalQueries.chronology()), input));
}
/**
* 根据年月返回当月所有日期列表
*
* @param year 年
* @param month 月
* @return 日期列表
*/
public static Vector<String> createDateArray(int year, int month) {
Vector<String> v = new Vector<String>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(year - ONE_THOUSENT_NINE_HUNDRED, month - 1, TEN));
int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
String startTime = String.valueOf(year) + "-"
+ (month < TEN ? "0" + month : month) + "-01";
Date st = formatter.parse(startTime, pos);
for (int i = 0; i < maxDay; i++) {
if (i > 0) {
st.setDate(st.getDate() + 1);
}
v.add(formatter.format(st));
}
return v;
}
@Test
public void test_reducedWithLateChronoChangeTwice() {
DateTimeFormatter df
= new DateTimeFormatterBuilder()
.appendValueReduced(YEAR, 2, 2, LocalDate.of(2000, 1, 1))
.appendLiteral(" ")
.appendChronologyId()
.appendLiteral(" ")
.appendChronologyId()
.toFormatter();
int expected = 2044;
String input = "44 ThaiBuddhist ISO";
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = df.parseUnresolved(input, pos);
assertEquals(pos.getIndex(), input.length(), "Input not parsed completely: " + pos);
assertEquals(pos.getErrorIndex(), -1, "Error index should be -1 (no-error)");
int actual = parsed.get(YEAR);
assertEquals(actual, expected,
String.format("Wrong date parsed, chrono: %s, input: %s",
parsed.query(TemporalQueries.chronology()), input));
}
@Override
public java.sql.Date read(JsonReader in) throws IOException {
switch (in.peek()) {
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try {
if (dateFormat != null) {
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
}
@Test(dataProvider="parseText")
public void test_parse_strict_caseInsensitive_parseLower(TemporalField field, TextStyle style, int value, String input) throws Exception {
setCaseSensitive(false);
ParsePosition pos = new ParsePosition(0);
assertEquals(getFormatter(field, style).parseUnresolved(input.toLowerCase(Locale.ROOT), pos).getLong(field), (long) value);
assertEquals(pos.getIndex(), input.length());
}
@Test(dataProvider="error")
public void test_parse_error(TemporalField field, int width, int baseValue, String text, int pos, Class<?> expected) {
try {
getFormatter0(field, width, baseValue).parseUnresolved(text, new ParsePosition(pos));
} catch (RuntimeException ex) {
assertTrue(expected.isInstance(ex));
}
}
@Test(dataProvider="bigOffsets")
public void test_parse_bigOffsets(String pattern, String parse, long offsetSecs) throws Exception {
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = getFormatter(pattern, "").parseUnresolved(parse, pos);
assertEquals(pos.getIndex(), parse.length());
assertEquals(parsed.getLong(OFFSET_SECONDS), offsetSecs);
}
/** Advance {@code pos} past any whitespace characters in {@code str},
* starting at the current parse position index.
* @param str the input string
* @param pos the current parse position
*/
private void consumeWhitespace(final String str, final ParsePosition pos) {
int idx = pos.getIndex();
final int len = str.length();
for (; idx < len; ++idx) {
if (!Character.isWhitespace(str.codePointAt(idx))) {
break;
}
}
pos.setIndex(idx);
}
@Test(dataProvider="FieldPatterns")
public void test_parse_textField(String pattern, String text, int pos, int expectedPos, long expectedValue) {
WeekFields weekDef = WeekFields.of(locale);
TemporalField field = null;
switch(pattern.charAt(0)) {
case 'e' :
field = weekDef.dayOfWeek();
break;
case 'w':
field = weekDef.weekOfWeekBasedYear();
break;
case 'W':
field = weekDef.weekOfMonth();
break;
case 'Y':
field = weekDef.weekBasedYear();
break;
default:
throw new IllegalStateException("bad format letter from pattern");
}
ParsePosition ppos = new ParsePosition(pos);
DateTimeFormatterBuilder b
= new DateTimeFormatterBuilder().appendPattern(pattern);
DateTimeFormatter dtf = b.toFormatter(locale);
TemporalAccessor parsed = dtf.parseUnresolved(text, ppos);
if (ppos.getErrorIndex() != -1) {
assertEquals(ppos.getErrorIndex(), expectedPos);
} else {
assertEquals(ppos.getIndex(), expectedPos, "Incorrect ending parse position");
long value = parsed.getLong(field);
assertEquals(value, expectedValue, "Value incorrect for " + field);
}
}
@Test(dataProvider="success")
public void test_parse_success(char c, boolean caseSensitive,
String text, int pos, int expectedPos) {
setCaseSensitive(caseSensitive);
ParsePosition ppos = new ParsePosition(pos);
TemporalAccessor parsed = getFormatter(c).parseUnresolved(text, ppos);
if (ppos.getErrorIndex() != -1) {
assertEquals(ppos.getIndex(), expectedPos);
} else {
assertEquals(ppos.getIndex(), expectedPos);
assertEquals(parsed.isSupported(YEAR), false);
assertEquals(parsed.query(TemporalQueries.chronology()), null);
assertEquals(parsed.query(TemporalQueries.zoneId()), null);
}
}
@Test(dataProvider="parseText")
public void test_parse_strict_caseInsensitive_parseUpper(TemporalField field, TextStyle style, int value, String input) throws Exception {
setCaseSensitive(false);
ParsePosition pos = new ParsePosition(0);
assertEquals(getFormatter(field, style).parseUnresolved(input.toUpperCase(Locale.ROOT), pos).getLong(field), (long) value);
assertEquals(pos.getIndex(), input.length());
}
@SuppressWarnings("unchecked")
private Object parseCompound(Number highValue, String source,
ParsePosition pos) throws ParseException {
Unit high = _unitFormat.parseSingleUnit(source, pos);
int i = pos.getIndex();
if (i >= source.length()
|| Character.isWhitespace(source.charAt(i)))
return measureOf(highValue, high);
Measure lowMeasure = (Measure) parseObject(source, pos);
Unit unit = lowMeasure.getUnit();
long l = lowMeasure.longValue(unit)
+ (long) high.getConverterTo(unit).convert(
highValue.longValue());
return Measure.valueOf(l, unit);
}
@Test(dataProvider = "ParseNothing")
public void test_parse_nothing(TemporalField field, int min, int max, boolean decimalPoint, String text, int pos, int expected) {
ParsePosition ppos = new ParsePosition(pos);
TemporalAccessor parsed = getFormatter(field, min, max, decimalPoint).parseUnresolved(text, ppos);
assertEquals(ppos.getErrorIndex(), expected);
assertEquals(parsed, null);
}
public static boolean isNumeric(String text) {
text = text.trim();
if (text.isEmpty()) {
return false;
}
ParsePosition pos = new ParsePosition(0);
getNumberFormat().parse(text, pos);
return text.length() == pos.getIndex();
}
@Test
public void test_adjacent_strict_firstVariableWidth_success() throws Exception {
// succeeds greedily parsing variable width, then fixed width, to non-numeric Z
DateTimeFormatter f = builder.appendValue(HOUR_OF_DAY).appendValue(MINUTE_OF_HOUR, 2).appendLiteral('Z').toFormatter(Locale.UK);
ParsePosition pp = new ParsePosition(0);
TemporalAccessor parsed = f.parseUnresolved("12309Z", pp);
assertEquals(pp.getErrorIndex(), -1);
assertEquals(pp.getIndex(), 6);
assertEquals(parsed.getLong(HOUR_OF_DAY), 123L);
assertEquals(parsed.getLong(MINUTE_OF_HOUR), 9L);
}
@Test(expectedExceptions=DateTimeParseException.class)
public void test_parse_CharSequence_ParsePosition_parseError() {
DateTimeFormatter test = DateTimeFormatter.ISO_DATE;
ParsePosition pos = new ParsePosition(3);
try {
test.parse("XXX2012XXX", pos);
fail();
} catch (DateTimeParseException ex) {
assertEquals(ex.getErrorIndex(), 7);
throw ex;
}
}
public void test_parse_caseSensitiveUTC_unmatchedCase() throws Exception {
setCaseSensitive(true);
ParsePosition pos = new ParsePosition(0);
TemporalAccessor parsed = getFormatter("+HH:MM:ss", "Z").parseUnresolved("z", pos);
assertEquals(pos.getErrorIndex(), 0);
assertEquals(parsed, null);
}
@Test(dataProvider="sample_isoOffsetDateTime")
public void test_parse_isoOffsetDateTime(
Integer year, Integer month, Integer day,
Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
String input, Class<?> invalid) {
if (input != null) {
Expected expected = createDateTime(year, month, day, hour, min, sec, nano);
buildCalendrical(expected, offsetId, null); // zone not expected to be parsed
assertParseMatch(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parseUnresolved(input, new ParsePosition(0)), expected);
}
}
@Test(dataProvider="parseStandaloneText")
public void test_parseStandaloneText(Locale locale, TemporalField field, TextStyle style, int expectedValue, String input) {
DateTimeFormatter formatter = getFormatter(field, style).withLocale(locale);
ParsePosition pos = new ParsePosition(0);
assertEquals(formatter.parseUnresolved(input, pos).getLong(field), (long) expectedValue);
assertEquals(pos.getIndex(), input.length());
}
@Test(dataProvider="sample_isoOffsetDate")
public void test_parse_isoOffsetDate(
Integer year, Integer month, Integer day, String offsetId, String zoneId,
String input, Class<?> invalid) {
if (input != null) {
Expected expected = createDate(year, month, day);
buildCalendrical(expected, offsetId, null); // zone not expected to be parsed
assertParseMatch(DateTimeFormatter.ISO_OFFSET_DATE.parseUnresolved(input, new ParsePosition(0)), expected);
}
}
@Test(dataProvider="sample_isoTime")
public void test_parse_isoTime(
Integer hour, Integer min, Integer sec, Integer nano, String offsetId, String zoneId,
String input, Class<?> invalid) {
if (input != null) {
Expected expected = createTime(hour, min, sec, nano);
if (offsetId != null) {
expected.add(ZoneOffset.of(offsetId));
}
assertParseMatch(DateTimeFormatter.ISO_TIME.parseUnresolved(input, new ParsePosition(0)), expected);
}
}
public void test_parse_noMatch2() throws Exception {
ParsePosition pos = new ParsePosition(3);
TemporalAccessor parsed =
getFormatter(DAY_OF_WEEK, TextStyle.FULL).parseUnresolved("Monday", pos);
assertEquals(pos.getErrorIndex(), 3);
assertEquals(parsed, null);
}
protected synchronized Double convertStringToNumber( String string ) throws HopValueException {
string = Const.trimToType( string, getTrimType() ); // see if trimming needs
// to be performed before
// conversion
if ( Utils.isEmpty( string ) ) {
return null;
}
try {
DecimalFormat format = getDecimalFormat( false );
Number number;
if ( lenientStringToNumber ) {
number = format.parse( string );
} else {
ParsePosition parsePosition = new ParsePosition( 0 );
number = format.parse( string, parsePosition );
if ( parsePosition.getIndex() < string.length() ) {
throw new HopValueException( toString()
+ " : couldn't convert String to number : non-numeric character found at position "
+ ( parsePosition.getIndex() + 1 ) + " for value [" + string + "]" );
}
}
return new Double( number.doubleValue() );
} catch ( Exception e ) {
throw new HopValueException( toString() + " : couldn't convert String to number ", e );
}
}