Java Code Examples for java.text.ParsePosition#setErrorIndex()
The following examples show how to use
java.text.ParsePosition#setErrorIndex() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MeasureFormat.java From microMathematics with GNU General Public License v3.0 | 6 votes |
@Override public Object parseObject(String source, ParsePosition pos) { int start = pos.getIndex(); try { int i = start; Number value = _numberFormat.parse(source, pos); if (i == pos.getIndex()) return null; // Cannot parse. i = pos.getIndex(); if (i >= source.length()) return measureOf(value, Unit.ONE); // No unit. boolean isCompound = !Character.isWhitespace(source.charAt(i)); if (isCompound) return parseCompound(value, source, pos); if (++i >= source.length()) return measureOf(value, Unit.ONE); // No unit. pos.setIndex(i); // Skips separator. Unit<?> unit = _unitFormat.parseProductUnit(source, pos); return measureOf(value, unit); } catch (ParseException e) { pos.setIndex(start); pos.setErrorIndex(e.getErrorOffset()); return null; } }
Example 2
Source File: MultiBenchmark.java From dateparser with MIT License | 5 votes |
Date parseDate(String text) { ParsePosition position = new ParsePosition(0); for (SimpleDateFormat format : FORMATs) { position.setIndex(0); position.setErrorIndex(-1); Date date = format.parse(text, position); if (position.getErrorIndex() > 0 || position.getIndex() != text.length()) { continue; } return date; } throw new IllegalArgumentException("Cannot parse: " + text); }
Example 3
Source File: TimeZoneFormat.java From fitnotifications with Apache License 2.0 | 5 votes |
/** * Parse an exemplar location string. * @param text the text contains an exemplar location string at the position. * @param pos the position. * @return The zone ID for the parsed exemplar location. */ private String parseExemplarLocation(String text, ParsePosition pos) { int startIdx = pos.getIndex(); int parsedPos = -1; String tzID = null; EnumSet<NameType> nameTypes = EnumSet.of(NameType.EXEMPLAR_LOCATION); Collection<MatchInfo> exemplarMatches = _tznames.find(text, startIdx, nameTypes); if (exemplarMatches != null) { MatchInfo exemplarMatch = null; for (MatchInfo match : exemplarMatches) { if (startIdx + match.matchLength() > parsedPos) { exemplarMatch = match; parsedPos = startIdx + match.matchLength(); } } if (exemplarMatch != null) { tzID = getTimeZoneID(exemplarMatch.tzID(), exemplarMatch.mzID()); pos.setIndex(parsedPos); } } if (tzID == null) { pos.setErrorIndex(startIdx); } return tzID; }
Example 4
Source File: TimeZoneFormat.java From fitnotifications with Apache License 2.0 | 5 votes |
/** * Parse a short zone ID. * @param text the text contains a time zone ID string at the position. * @param pos the position. * @return The zone ID for the parsed short zone ID. */ private static String parseShortZoneID(String text, ParsePosition pos) { String resolvedID = null; if (SHORT_ZONE_ID_TRIE == null) { synchronized (TimeZoneFormat.class) { if (SHORT_ZONE_ID_TRIE == null) { // Build short zone ID trie TextTrieMap<String> trie = new TextTrieMap<String>(true); Set<String> canonicalIDs = TimeZone.getAvailableIDs(SystemTimeZoneType.CANONICAL, null, null); for (String id : canonicalIDs) { String shortID = ZoneMeta.getShortID(id); if (shortID != null) { trie.put(shortID, id); } } // Canonical list does not contain Etc/Unknown trie.put(UNKNOWN_SHORT_ZONE_ID, UNKNOWN_ZONE_ID); SHORT_ZONE_ID_TRIE = trie; } } } int[] matchLen = new int[] {0}; Iterator<String> itr = SHORT_ZONE_ID_TRIE.get(text, pos.getIndex(), matchLen); if (itr != null) { resolvedID = itr.next(); pos.setIndex(pos.getIndex() + matchLen[0]); } else { pos.setErrorIndex(pos.getIndex()); } return resolvedID; }
Example 5
Source File: DateTimeFormatter.java From Bytecoder with Apache License 2.0 | 5 votes |
private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); DateTimeParseContext context = new DateTimeParseContext(this); int pos = position.getIndex(); pos = printerParser.parse(context, text, pos); if (pos < 0) { position.setErrorIndex(~pos); // index not updated from input return null; } position.setIndex(pos); // errorIndex not updated from input return context; }
Example 6
Source File: DateTimeFormatter.java From desugar_jdk_libs with GNU General Public License v2.0 | 5 votes |
private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); DateTimeParseContext context = new DateTimeParseContext(this); int pos = position.getIndex(); pos = printerParser.parse(context, text, pos); if (pos < 0) { position.setErrorIndex(~pos); // index not updated from input return null; } position.setIndex(pos); // errorIndex not updated from input return context; }
Example 7
Source File: DateTimeFormatter.java From JDKSourceCode1.8 with MIT License | 5 votes |
private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); DateTimeParseContext context = new DateTimeParseContext(this); int pos = position.getIndex(); pos = printerParser.parse(context, text, pos); if (pos < 0) { position.setErrorIndex(~pos); // index not updated from input return null; } position.setIndex(pos); // errorIndex not updated from input return context; }
Example 8
Source File: DateTimeFormatter.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); DateTimeParseContext context = new DateTimeParseContext(this); int pos = position.getIndex(); pos = printerParser.parse(context, text, pos); if (pos < 0) { position.setErrorIndex(~pos); // index not updated from input return null; } position.setIndex(pos); // errorIndex not updated from input return context; }
Example 9
Source File: UnitFormat.java From microMathematics with GNU General Public License v3.0 | 5 votes |
/** * Parses the text from a string to produce an object * (implements <code>java.text.Format</code>). * * @param source the string source, part of which should be parsed. * @param pos the cursor position. * @return the corresponding unit or <code>null</code> if the string * cannot be parsed. */ public final Unit<?> parseObject(String source, ParsePosition pos) { int start = pos.getIndex(); try { return parseProductUnit(source, pos); } catch (ParseException e) { pos.setIndex(start); pos.setErrorIndex(e.getErrorOffset()); return null; } }
Example 10
Source File: DateTimeFormatter.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private DateTimeParseContext parseUnresolved0(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); DateTimeParseContext context = new DateTimeParseContext(this); int pos = position.getIndex(); pos = printerParser.parse(context, text, pos); if (pos < 0) { position.setErrorIndex(~pos); // index not updated from input return null; } position.setIndex(pos); // errorIndex not updated from input return context; }
Example 11
Source File: SimpleTimestampFormat.java From hop with Apache License 2.0 | 5 votes |
/** * Parses text from a string to produce a <code>Timestamp</code>. * <p/> * The method attempts to parse text starting at the index given by <code>pos</code>. If parsing succeeds, then the * index of <code>pos</code> is updated to the index after the last character used (parsing does not necessarily use * all characters up to the end of the string), and the parsed date is returned. The updated <code>pos</code> can be * used to indicate the starting point for the next call to this method. If an error occurs, then the index of * <code>pos</code> is not changed, the error index of <code>pos</code> is set to the index of the character where the * error occurred, and null is returned. * <p/> * <p>This parsing operation uses the {@link SimpleDateFormat#calendar calendar} to produce a {@code Date}. All of the * {@code calendar}'s date-time fields are {@linkplain java.util.Calendar#clear() cleared} before parsing, and the * {@code calendar}'s default values of the date-time fields are used for any missing date-time information. For * example, the year value of the parsed {@code Date} is 1970 with {@link java.util.GregorianCalendar} if no year * value is given from the parsing operation. The {@code TimeZone} value may be overwritten, depending on the given * pattern and the time zone value in {@code text}. Any {@code TimeZone} value that has previously been set by a call * to {@link #setTimeZone(java.util.TimeZone) setTimeZone} may need to be restored for further operations. * * @param text A <code>String</code>, part of which should be parsed. * @param pos A <code>ParsePosition</code> object with index and error index information as described above. * @return A <code>Date</code> parsed from the string. In case of error, returns null. * @throws NullPointerException if <code>text</code> or <code>pos</code> is null. */ @Override public Date parse( String text, ParsePosition pos ) { String timestampFormatDate; Date tempDate; if ( compatibleToSuperPattern ) { tempDate = super.parse( text, pos ); return new Timestamp( tempDate.getTime() ); } StringBuilder dateText = new StringBuilder( text.substring( pos.getIndex() ) ); ParsePosition positionError = new ParsePosition( 0 ); tempDate = super.parse( dateText.toString(), positionError ); if ( tempDate != null ) { pos.setErrorIndex( pos.getIndex() ); return null; } int startNanosecondsPosition = positionError.getErrorIndex(); int endNanosecondsPosition = endNanosecondPatternPosition - startNanosecondPatternPosition + 1 + startNanosecondsPosition; endNanosecondsPosition = ( endNanosecondsPosition >= dateText.length() ) ? dateText.length() : endNanosecondsPosition; String nanoseconds = String.valueOf( dateText.subSequence( startNanosecondsPosition, endNanosecondsPosition ) ); dateText.delete( startNanosecondsPosition, endNanosecondsPosition ); ParsePosition position = new ParsePosition( 0 ); dateText.append( NANOSECOND_PLACEHOLDER ); tempDate = super.parse( dateText.toString(), position ); if ( tempDate == null ) { pos.setErrorIndex( position.getErrorIndex() ); return null; } timestampFormatDate = defaultTimestampFormat.format( tempDate ); String result = timestampFormatDate + '.' + nanoseconds; Timestamp res = Timestamp.valueOf( timestampFormatDate + '.' + nanoseconds ); pos.setIndex( pos.getIndex() + result.length() ); return res; }
Example 12
Source File: TimeUnitFormat.java From fitnotifications with Apache License 2.0 | 4 votes |
/** * Parse a TimeUnitAmount. * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) * @deprecated ICU 53 see {@link MeasureFormat}. */ @Deprecated @Override public TimeUnitAmount parseObject(String source, ParsePosition pos) { if (!isReady) { setup(); } Number resultNumber = null; TimeUnit resultTimeUnit = null; int oldPos = pos.getIndex(); int newPos = -1; int longestParseDistance = 0; String countOfLongestMatch = null; // we don't worry too much about speed on parsing, but this can be optimized later if needed. // Parse by iterating through all available patterns // and looking for the longest match. for (TimeUnit timeUnit : timeUnitToCountToPatterns.keySet()) { Map<String, Object[]> countToPattern = timeUnitToCountToPatterns.get(timeUnit); for (Entry<String, Object[]> patternEntry : countToPattern.entrySet()) { String count = patternEntry.getKey(); for (int styl = FULL_NAME; styl < TOTAL_STYLES; ++styl) { MessageFormat pattern = (MessageFormat) (patternEntry.getValue())[styl]; pos.setErrorIndex(-1); pos.setIndex(oldPos); // see if we can parse Object parsed = pattern.parseObject(source, pos); if (pos.getErrorIndex() != -1 || pos.getIndex() == oldPos) { // nothing parsed continue; } Number temp = null; if (((Object[]) parsed).length != 0) { // pattern with Number as beginning, // such as "{0} d". // check to make sure that the timeUnit is consistent Object tempObj = ((Object[]) parsed)[0]; if (tempObj instanceof Number) { temp = (Number) tempObj; } else { // 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. try { temp = format.parse(tempObj.toString()); } catch (ParseException e) { continue; } } } int parseDistance = pos.getIndex() - oldPos; if (parseDistance > longestParseDistance) { resultNumber = temp; resultTimeUnit = timeUnit; newPos = pos.getIndex(); longestParseDistance = parseDistance; countOfLongestMatch = count; } } } } /* * 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 if (countOfLongestMatch.equals("zero")) { resultNumber = Integer.valueOf(0); } else if (countOfLongestMatch.equals("one")) { resultNumber = Integer.valueOf(1); } else if (countOfLongestMatch.equals("two")) { resultNumber = Integer.valueOf(2); } else { // should not happen. // TODO: how to handle? resultNumber = Integer.valueOf(3); } } if (longestParseDistance == 0) { pos.setIndex(oldPos); pos.setErrorIndex(0); return null; } else { pos.setIndex(newPos); pos.setErrorIndex(-1); return new TimeUnitAmount(resultNumber, resultTimeUnit); } }
Example 13
Source File: TimeZoneFormat.java From fitnotifications with Apache License 2.0 | 4 votes |
/** * Returns offset from GMT(UTC) in milliseconds for the given localized GMT * offset format string. When the given string cannot be parsed, this method * sets the current position as the error index to <code>ParsePosition pos</code> * and returns 0. * * @param text the text contains a localized GMT offset string at the position. * @param pos the position. * @param isShort true if this parser to try the short format first * @param hasDigitOffset receiving if the parsed zone string contains offset digits. * @return the offset from GMT(UTC) in milliseconds for the given localized GMT * offset format string. */ private int parseOffsetLocalizedGMT(String text, ParsePosition pos, boolean isShort, Output<Boolean> hasDigitOffset) { int start = pos.getIndex(); int offset = 0; int[] parsedLength = {0}; if (hasDigitOffset != null) { hasDigitOffset.value = false; } offset = parseOffsetLocalizedGMTPattern(text, start, isShort, parsedLength); // For now, parseOffsetLocalizedGMTPattern handles both long and short // formats, no matter isShort is true or false. This might be changed in future // when strict parsing is necessary, or different set of patterns are used for // short/long formats. // if (parsedLength[0] == 0) { // offset = parseOffsetLocalizedGMTPattern(text, start, !isShort, parsedLength); // } if (parsedLength[0] > 0) { if (hasDigitOffset != null) { hasDigitOffset.value = true; } pos.setIndex(start + parsedLength[0]); return offset; } // Try the default patterns offset = parseOffsetDefaultLocalizedGMT(text, start, parsedLength); if (parsedLength[0] > 0) { if (hasDigitOffset != null) { hasDigitOffset.value = true; } pos.setIndex(start + parsedLength[0]); return offset; } // Check if this is a GMT zero format if (text.regionMatches(true, start, _gmtZeroFormat, 0, _gmtZeroFormat.length())) { pos.setIndex(start + _gmtZeroFormat.length()); return 0; } // Check if this is a default GMT zero format for (String defGMTZero : ALT_GMT_STRINGS) { if (text.regionMatches(true, start, defGMTZero, 0, defGMTZero.length())) { pos.setIndex(start + defGMTZero.length()); return 0; } } // Nothing matched pos.setErrorIndex(start); return 0; }
Example 14
Source File: TimeZoneFormat.java From fitnotifications with Apache License 2.0 | 4 votes |
/** * Returns offset from GMT(UTC) in milliseconds for the given ISO 8601 time zone string * (basic format, extended format, or UTC indicator). When the given string is not an ISO 8601 time * zone string, this method sets the current position as the error index * to <code>ParsePosition pos</code> and returns 0. * * @param text the text contains ISO 8601 style time zone string (e.g. "-08", "-08:00", "Z") * at the position. * @param pos the position. * @param extendedOnly <code>true</code> if parsing the text as ISO 8601 extended offset format (e.g. "-08:00"), * or <code>false</code> to evaluate the text as basic format. * @param hasDigitOffset receiving if the parsed zone string contains offset digits. * @return the offset from GMT(UTC) in milliseconds for the given ISO 8601 style * time zone string. */ private static int parseOffsetISO8601(String text, ParsePosition pos, boolean extendedOnly, Output<Boolean> hasDigitOffset) { if (hasDigitOffset != null) { hasDigitOffset.value = false; } int start = pos.getIndex(); if (start >= text.length()) { pos.setErrorIndex(start); return 0; } char firstChar = text.charAt(start); if (Character.toUpperCase(firstChar) == ISO8601_UTC.charAt(0)) { // "Z" - indicates UTC pos.setIndex(start + 1); return 0; } int sign; if (firstChar == '+') { sign = 1; } else if (firstChar == '-') { sign = -1; } else { // Not an ISO 8601 offset string pos.setErrorIndex(start); return 0; } ParsePosition posOffset = new ParsePosition(start + 1); int offset = parseAsciiOffsetFields(text, posOffset, ':', OffsetFields.H, OffsetFields.HMS); if (posOffset.getErrorIndex() == -1 && !extendedOnly && (posOffset.getIndex() - start <= 3)) { // If the text is successfully parsed as extended format with the options above, it can be also parsed // as basic format. For example, "0230" can be parsed as offset 2:00 (only first digits are valid for // extended format), but it can be parsed as offset 2:30 with basic format. We use longer result. ParsePosition posBasic = new ParsePosition(start + 1); int tmpOffset = parseAbuttingAsciiOffsetFields(text, posBasic, OffsetFields.H, OffsetFields.HMS, false); if (posBasic.getErrorIndex() == -1 && posBasic.getIndex() > posOffset.getIndex()) { offset = tmpOffset; posOffset.setIndex(posBasic.getIndex()); } } if (posOffset.getErrorIndex() != -1) { pos.setErrorIndex(start); return 0; } pos.setIndex(posOffset.getIndex()); if (hasDigitOffset != null) { hasDigitOffset.value = true; } return sign * offset; }
Example 15
Source File: TimeZoneFormat.java From fitnotifications with Apache License 2.0 | 4 votes |
/** * Parses offset represented by contiguous ASCII digits * <p> * Note: This method expects the input position is already at the start of * ASCII digits and does not parse sign (+/-). * * @param text The text contains a sequence of ASCII digits * @param pos The parse position * @param minFields The minimum Fields to be parsed * @param maxFields The maximum Fields to be parsed * @param fixedHourWidth true if hours field must be width of 2 * @return Parsed offset, 0 or positive number. */ private static int parseAbuttingAsciiOffsetFields(String text, ParsePosition pos, OffsetFields minFields, OffsetFields maxFields, boolean fixedHourWidth) { int start = pos.getIndex(); int minDigits = 2 * (minFields.ordinal() + 1) - (fixedHourWidth ? 0 : 1); int maxDigits = 2 * (maxFields.ordinal() + 1); int[] digits = new int[maxDigits]; int numDigits = 0; int idx = start; while (numDigits < digits.length && idx < text.length()) { int digit = ASCII_DIGITS.indexOf(text.charAt(idx)); if (digit < 0) { break; } digits[numDigits] = digit; numDigits++; idx++; } if (fixedHourWidth && ((numDigits & 1) != 0)) { // Fixed digits, so the number of digits must be even number. Truncating. numDigits--; } if (numDigits < minDigits) { pos.setErrorIndex(start); return 0; } int hour = 0, min = 0, sec = 0; boolean bParsed = false; while (numDigits >= minDigits) { switch (numDigits) { case 1: //H hour = digits[0]; break; case 2: //HH hour = digits[0] * 10 + digits[1]; break; case 3: //Hmm hour = digits[0]; min = digits[1] * 10 + digits[2]; break; case 4: //HHmm hour = digits[0] * 10 + digits[1]; min = digits[2] * 10 + digits[3]; break; case 5: //Hmmss hour = digits[0]; min = digits[1] * 10 + digits[2]; sec = digits[3] * 10 + digits[4]; break; case 6: //HHmmss hour = digits[0] * 10 + digits[1]; min = digits[2] * 10 + digits[3]; sec = digits[4] * 10 + digits[5]; break; } if (hour <= MAX_OFFSET_HOUR && min <= MAX_OFFSET_MINUTE && sec <= MAX_OFFSET_SECOND) { // Successfully parsed bParsed = true; break; } // Truncating numDigits -= (fixedHourWidth ? 2 : 1); hour = min = sec = 0; } if (!bParsed) { pos.setErrorIndex(start); return 0; } pos.setIndex(start + numDigits); return ((((hour * 60) + min) * 60) + sec) * 1000; }
Example 16
Source File: 1_FastDateFormat.java From SimFix with GNU General Public License v2.0 | 2 votes |
/** * <p>Parsing is not supported.</p> * * @param source the string to parse * @param pos the parsing position * @return <code>null</code> as not supported */ public Object parseObject(String source, ParsePosition pos) { pos.setIndex(0); pos.setErrorIndex(0); return null; }
Example 17
Source File: 1_FastDateFormat.java From SimFix with GNU General Public License v2.0 | 2 votes |
/** * <p>Parsing is not supported.</p> * * @param source the string to parse * @param pos the parsing position * @return <code>null</code> as not supported */ public Object parseObject(String source, ParsePosition pos) { pos.setIndex(0); pos.setErrorIndex(0); return null; }
Example 18
Source File: 1_FastDateFormat.java From SimFix with GNU General Public License v2.0 | 2 votes |
/** * <p>Parsing is not supported.</p> * * @param source the string to parse * @param pos the parsing position * @return <code>null</code> as not supported */ public Object parseObject(String source, ParsePosition pos) { pos.setIndex(0); pos.setErrorIndex(0); return null; }
Example 19
Source File: 1_FastDateFormat.java From SimFix with GNU General Public License v2.0 | 2 votes |
/** * <p>Parsing is not supported.</p> * * @param source the string to parse * @param pos the parsing position * @return <code>null</code> as not supported */ public Object parseObject(String source, ParsePosition pos) { pos.setIndex(0); pos.setErrorIndex(0); return null; }
Example 20
Source File: 1_FastDateFormat.java From SimFix with GNU General Public License v2.0 | 2 votes |
/** * <p>Parsing is not supported.</p> * * @param source the string to parse * @param pos the parsing position * @return <code>null</code> as not supported */ public Object parseObject(String source, ParsePosition pos) { pos.setIndex(0); pos.setErrorIndex(0); return null; }