/** * Checks if the value can safely be converted to a byte primitive. * * @param value The value validation is being performed on. * @param locale The locale to use to parse the number (system default if null) * @return the converted Byte value. */ public static Byte formatByte(String value, Locale locale) { Byte result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length() && num.doubleValue() >= Byte.MIN_VALUE && num.doubleValue() <= Byte.MAX_VALUE) { result = new Byte(num.byteValue()); } } return result; }
/** * Parses date given in parameter according the ISO-8601 standard. This parameter should follow a * syntax defined in the {@link #PATTERNS} array to be validated. * * @param value The date to parse. * @return A date found in the request. * @throws ParseException if the string can not be parsed. */ static Object getFuzzyDate(final String value) throws ParseException { String computedValue = value; // special handling for current keyword (we accept both wms and wcs ways) if (computedValue.equalsIgnoreCase("current") || computedValue.equalsIgnoreCase("now")) { return null; } // Accept new "present" keyword, which actually fills in present time as now should have if (computedValue.equalsIgnoreCase("present")) { Calendar now = Calendar.getInstance(); now.set(Calendar.MILLISECOND, 0); computedValue = FormatAndPrecision.MILLISECOND.getFormat().format(now.getTime()); } for (FormatAndPrecision f : FormatAndPrecision.values()) { ParsePosition pos = new ParsePosition(0); Date time = f.getFormat().parse(computedValue, pos); if (pos.getIndex() == computedValue.length()) { DateRange range = f.expand(time); if (range.getMinValue().equals(range.getMaxValue())) { return range.getMinValue(); } else { return range; } } } throw new ParseException("Invalid date: " + value, 0); }
private static Date parseDateWithLeniency(String str, String[] parsePatterns, boolean lenient) throws ParseException { if ((str == null) || (parsePatterns == null)) { throw new IllegalArgumentException("Date and Patterns must not be null"); } SimpleDateFormat parser = new SimpleDateFormat(); parser.setLenient(lenient); ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { String pattern = parsePatterns[i]; if (parsePatterns[i].endsWith("ZZ")) { pattern = pattern.substring(0, pattern.length() - 1); } parser.applyPattern(pattern); pos.setIndex(0); String str2 = str; if (parsePatterns[i].endsWith("ZZ")) { int signIdx = indexOfSignChars(str2, 0); while (signIdx >= 0) { str2 = reformatTimezone(str2, signIdx); signIdx = indexOfSignChars(str2, ++signIdx); } } Date date = parser.parse(str2, pos); if ((date != null) && (pos.getIndex() == str2.length())) { return date; } } throw new ParseException("Unable to parse the date: " + str, -1); }
public void outputValues(String[] values) { if (values.length > 1) { writer.print("["); } for (int i = 0; i < values.length; i++) { String value = values[i]; if (i > 0) { writer.print(", "); } if (value == null || value.length() == 0) { writer.print("null"); } else { // Is it a number? ParsePosition pos = new ParsePosition(0); formatter.parse(value, pos); if (value.length() == pos.getIndex()) { // It's a number. Remove leading zeros and output value = value.replaceFirst("^0+(\\d)", "$1"); writer.print(value); } else { // Not a number, escape it gson.toJson(value, writer); } } } if (values.length > 1) { writer.print("]"); } }
@Override public Object parseObject(String text, ParsePosition pos) { Objects.requireNonNull(text, "text"); DateTimeBuilder builder; try { builder = formatter.parseToBuilder(text, pos); } catch (IndexOutOfBoundsException ex) { if (pos.getErrorIndex() < 0) { pos.setErrorIndex(0); } return null; } if (builder == null) { if (pos.getErrorIndex() < 0) { pos.setErrorIndex(0); } return null; } if (parseType == null) { return builder; } try { return builder.resolve().build(parseType); } catch (RuntimeException ex) { pos.setErrorIndex(0); return null; } }
public Date parse(String source, ParsePosition pos) { calendar.clear(); int p = 0; try { String s = parseTZ(source); int l = s.length(); calendar.set(Calendar.YEAR, Integer.parseInt(s.substring(p, p + 4))); p += 4; if (l > p) { if (!Character.isDigit(s.charAt(p))) { ++p; } calendar.set(Calendar.MONTH, Integer.parseInt(s.substring(p, p + 2)) - 1); p += 2; if (l > p) { if (!Character.isDigit(s.charAt(p))) { ++p; } calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(s.substring(p, p + 2))); p += 2; if (l > p) { if (!Character.isDigit(s.charAt(p))) { ++p; } calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(s.substring(p, p + 2))); p += 2; if (l > p) { if (s.charAt(p) == ':') { ++p; } calendar.set(Calendar.MINUTE, Integer.parseInt(s.substring(p, p + 2))); p += 2; if (l > p) { if (s.charAt(p) == ':') { ++p; } calendar.set(Calendar.SECOND, Integer.parseInt(s.substring(p))); } else { clearCalendarFields(Calendar.SECOND); } } else { clearCalendarFields(Calendar.MINUTE); } } else { clearCalendarFields(Calendar.HOUR_OF_DAY); } } else { clearCalendarFields(Calendar.DAY_OF_MONTH); } } else { clearCalendarFields(Calendar.MONTH); } pos.setIndex(source.length()); return calendar.getTime(); } catch (Exception e) { pos.setErrorIndex(p); return null; } }
/** * Looks at the start of a string for a day (defined in the user's locale). If found, returns * String array containing the match (1st elem) and the remaining string (2nd elem). Otherwise, * returns null. * * @param input * @return */ @Override public String[] find(final String input) { result = null; pos.setIndex(0); result = sdf.parse(input, pos); if (result == null) return null; return new String[] {input.substring(0, pos.getIndex()), input.substring(pos.getIndex())}; }
private Number parseNumber(String val, NumberFormat numFormat) throws ParseException { final ParsePosition parsePos = new ParsePosition(0); final Number num = numFormat.parse(val, parsePos); if (parsePos.getIndex() != val.length()) { throw new ParseException("illegal number format", parsePos.getIndex()); } return num; }
public void testPartialParse() throws Exception { java.text.ParsePosition pos = new java.text.ParsePosition(0); String timestamp = "2007-08-13T19:51:23Z"; Date result = df.parse(timestamp + "hello", pos); assertEquals(date, result); assertEquals(timestamp.length(), pos.getIndex()); }
public static boolean isAmount(String value) { if (StringUtils.isEmpty(value)) { return false; } ParsePosition pos = new ParsePosition(0); new DecimalFormat(Constants.AMOUNT_FORMAT).parse(value, pos); return pos.getIndex() == value.length(); }
public static Date parseDatetime(String str) { for (String formatStr : DATETIME_FORMATS) { SimpleDateFormat fmt = new SimpleDateFormat(formatStr); fmt.setLenient(false); ParsePosition pp = new ParsePosition(0); Date d = fmt.parse(str, pp); if (d != null && pp.getIndex() == str.length()) return d; } return null; }
/** * Parses a string using {@link SimpleDateFormat} and a given pattern. The entire string must * match the pattern specified. * * @param s string to be parsed * @param pattern {@link SimpleDateFormat} pattern * @param tz time zone in which to interpret string. Defaults to the Java default time zone * @return a Calendar initialized with the parsed value, or null if parsing failed. If returned, * the Calendar is configured to the GMT time zone. */ public static Calendar parseDateFormat(String s, String pattern, TimeZone tz) { assert pattern != null; ParsePosition pp = new ParsePosition(0); Calendar ret = parseDateFormat(s, pattern, tz, pp); if (pp.getIndex() != s.length()) { // Didn't consume entire string - not good return null; } return ret; }
@Override public Object parseObject(String source, ParsePosition pos) { try { T result = (T) Enum.valueOf(enumClass, StringUtils.naturalToSymbol(source)); pos.setIndex(source.length()); return result; } catch (Exception e) { pos.setErrorIndex(0); return null; } }
/** * @generated */ public IParserEditStatus isValidEditString(IAdaptable adapter, String editString) { ParsePosition pos = new ParsePosition(0); Object[] values = getEditProcessor().parse(editString, pos); if (values == null) { return new ParserEditStatus(ScribbleDiagramEditorPlugin.ID, IParserEditStatus.UNEDITABLE, NLS.bind( Messages.MessageFormatParser_InvalidInputError, new Integer(pos.getErrorIndex()))); } return validateNewValues(values); }
/** * Parses the text to a builder. * * <p>This parses to a {@code DateTimeBuilder} but does not require the input to be fully parsed. * * <p>This method does not throw {@link DateTimeParseException}. Instead, errors are returned * within the state of the specified parse position. Callers must check for errors before using * the context. * * <p>This method may throw some other {@code DateTimeException} if a date/time problem occurs. * * @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, not null * @return the parsed text, null only if the parse results in an error * @throws IndexOutOfBoundsException if the position is invalid * @throws DateTimeParseException if the parse fails * @throws DateTimeException if there is a date/time problem */ public DateTimeBuilder parseToBuilder(CharSequence text, ParsePosition position) { Objects.requireNonNull(text, "text"); Objects.requireNonNull(position, "position"); DateTimeParseContext context = new DateTimeParseContext(locale, symbols); int pos = position.getIndex(); pos = printerParser.parse(context, text, pos); if (pos < 0) { position.setErrorIndex(~pos); return null; } position.setIndex(pos); return context.toBuilder(); }
/** * Parses the text to a builder. * * <p>This parses to a {@code DateTimeBuilder} ensuring that the text is fully parsed. This method * throws {@link DateTimeParseException} if unable to parse, or some other {@code * DateTimeException} if another date/time problem occurs. * * @param text the text to parse, not null * @return the engine representing the result of the parse, not null * @throws DateTimeParseException if the parse fails * @throws DateTimeException if there is a date/time problem */ public DateTimeBuilder parseToBuilder(CharSequence text) { Objects.requireNonNull(text, "text"); String str = text.toString(); // parsing whole String, so this makes sense ParsePosition pos = new ParsePosition(0); DateTimeBuilder result = parseToBuilder(str, pos); if (result == null || pos.getErrorIndex() >= 0 || pos.getIndex() < str.length()) { String abbr = str.toString(); if (abbr.length() > 64) { abbr = abbr.substring(0, 64) + "..."; } if (pos.getErrorIndex() >= 0) { throw new DateTimeParseException( "Text '" + abbr + "' could not be parsed at index " + pos.getErrorIndex(), str, pos.getErrorIndex()); } else { throw new DateTimeParseException( "Text '" + abbr + "' could not be parsed, unparsed text found at index " + pos.getIndex(), str, pos.getIndex()); } } return result; }
/** * Parses the supplied string to see if it looks like a date. If so, returns the date. Otherwise, * returns null. */ public static Date parseDate(String string) { ParsePosition parsePosition = new ParsePosition(0); for (int i = 0; i < DATE_FORMATS.length; i++) { SimpleDateFormat f = DATE_FORMATS[i]; synchronized (f) { parsePosition.setIndex(0); Date date = f.parse(string, parsePosition); if (parsePosition.getIndex() == string.length()) { return date; } } } return null; }
protected String isCorrectString(String value) { String text = value.trim(); if (sMinValue.equalsIgnoreCase(text) || sMaxValue.equalsIgnoreCase(text)) return null; Number result = null; if ((fNumberType == DOUBLE || fNumberType == FLOAT) && (text.indexOf('e') != -1 || text.indexOf('E') != -1)) { // We have a double/float with an exponent. This is scientific notation. Formatter handles // them badly, so use parse instead. try { if (fNumberType == DOUBLE) { result = new Double(Double.parseDouble(text)); } else { result = new Float(Float.parseFloat(text)); } } catch (NumberFormatException e) { } } else { // integral or not scientific notation. Let formatter handle it. ParsePosition parsePosition = new ParsePosition(0); result = fFormatter.parse(text, parsePosition); if (parsePosition.getErrorIndex() != -1 || parsePosition.getIndex() != text.length()) result = null; // Some error // Check for out of bounds with long type if (fNumberType == LONG && result instanceof Double) { result = (result.doubleValue() < 0) ? MinmaxValidator.LONG_UNDERFLOW : MinmaxValidator.LONG_OVERFLOW; } } if (result != null) { // Now see if it is valid for the requested type. MinmaxValidator v = sMinMaxValidators[fNumberType]; // Double/Float are special because the min/MIN are on the absolute value, not signed value. if (fNumberType == DOUBLE || fNumberType == FLOAT) { double d = result.doubleValue(); if (d == 0.0 || d == -0.0) return null; // +/- zero are valid values. result = new Double(Math.abs(d)); } if (v != null) { String e = v.isValid(result); if (e == null || e.length() == 0) return null; return e; // It didn't fit in a the number type. } } return (fFormatter.isParseIntegerOnly() ? sNotIntegerError : sNotNumberError); }
/** * Parse the input using a NumberFormatter. If the number cannot be parsed, the error key * <em>number.invalidNumber</em> will be added to the errors. */ protected Number parse(String input, Collection<ValidationError> errors) { input = preprocess(input); ParsePosition pp = new ParsePosition(0); for (NumberFormat format : this.formats) { pp.setIndex(0); Number number = format.parse(input, pp); if (number != null && input.length() == pp.getIndex()) return number; } // If we've gotten here we could not parse the number errors.add(new ScopedLocalizableError("converter.number", "invalidNumber")); return null; }
@Override public Object fromString(final String value, final Locale locale) { ParsePosition parsePosition = new ParsePosition(0); String trimedValue = value.replaceAll(" ", ""); DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(locale); formatter.setParseBigDecimal(true); Object parsedValue = formatter.parseObject(trimedValue, parsePosition); if (parsePosition.getIndex() == trimedValue.length()) { return parsedValue; } return value; }
/** Does the parse-work without the mandatory-check */ private String parse2(String external) throws FmtParseException { // trim blanks on both sides if (external == null) return ""; external = external.trim(); if (external.length() == 0) return ""; else { ParsePosition pp = new ParsePosition(0); Date date = null; date = dateFormat_.parse(external, pp); if (date == null || (pp.getIndex() != external.length() && pp.getIndex() > 0)) { throw new FmtParseException("ATSSyntax", getSampleTS()); } return TimeStampUtil.date2Internal(date); } }
protected void load() throws IOException { BufferedReader is = new BufferedReader(new FileReader("ReminderService.txt")); SimpleDateFormat formatter = new SimpleDateFormat("yyyy MM dd hh mm"); String aLine; while ((aLine = is.readLine()) != null) { ParsePosition pp = new ParsePosition(0); Date date = formatter.parse(aLine, pp); if (date == null) { message("Invalid date in " + aLine); continue; } String mesg = aLine.substring(pp.getIndex()); l.add(new Item(date, mesg)); } }
@Override public Result<Date> convertToModel(String value, ValueContext context) { if (value == null) { return Result.ok(null); } // Remove leading and trailing white space value = value.trim(); ParsePosition parsePosition = new ParsePosition(0); Date parsedValue = getFormat(context.getLocale().orElse(null)).parse(value, parsePosition); if (parsePosition.getIndex() != value.length()) { return Result.error("Could not convert '" + value); } return Result.ok(parsedValue); }
/** * Attempts to pass a HTTP date. * * @param date The date to parse * @return The parsed date, or null if parsing failed */ public static Date parseDate(final String date) { /* IE9 sends a superflous lenght parameter after date in the If-Modified-Since header, which needs to be stripped before parsing. */ final int semicolonIndex = date.indexOf(';'); final String trimmedDate = semicolonIndex >= 0 ? date.substring(0, semicolonIndex) : date; ParsePosition pp = new ParsePosition(0); SimpleDateFormat dateFormat = RFC1123_PATTERN_FORMAT.get(); Date val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(RFC1036_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(ASCITIME_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } pp = new ParsePosition(0); dateFormat = new SimpleDateFormat(OLD_COOKIE_PATTERN, LOCALE_US); dateFormat.setTimeZone(GMT_ZONE); val = dateFormat.parse(trimmedDate, pp); if (val != null && pp.getIndex() == trimmedDate.length()) { return val; } return null; }
public static Date parseDate(String dateStr, String... parsePatterns) throws ParseException { if (dateStr == null || parsePatterns == null) { throw new IllegalArgumentException("Date and Patterns must not be null"); } String strDate = dateStr; // do year correction. (partial year >=50 will be 1999 and <50 will be 2000) String[] parts = StringUtils.split(dateStr, '/'); int len = parts.length; if (len != 3 || parts[0].length() > 2 || parts[1].length() > 2) throw new ParseException("Unable to parse the date " + strDate, -1); String yStr = parts[2]; if (!(yStr.length() == 4 || yStr.length() == 2 || yStr.length() == 10)) throw new ParseException("Unable to parse the date " + strDate, -1); if (yStr.length() == 2 && StringUtils.isNumeric(yStr)) { if (Integer.parseInt(yStr) < 50) yStr = "20" + yStr; else yStr = "19" + yStr; parts[2] = yStr; strDate = StringUtils.join(parts, '/'); } // BJ: date formats are not thread save, so we need to create one each time. SimpleDateFormat parser = null; ParsePosition pos = new ParsePosition(0); for (int i = 0; i < parsePatterns.length; i++) { if (i == 0) { parser = new SimpleDateFormat(parsePatterns[0]); } else { parser.applyPattern(parsePatterns[i]); } pos.setIndex(0); Date date = parser.parse(strDate, pos); if (date != null && pos.getIndex() == strDate.length()) { return date; } } throw new ParseException("Unable to parse the date: " + strDate, -1); }
@Override public Object parseObject(String s, ParsePosition pos) { if (pos.getErrorIndex() >= 0) throw new IllegalArgumentException(pos + " has en error at " + pos.getErrorIndex()); boolean success = false; Object tmpRes = null; final ParsePosition tmpPos = new ParsePosition(pos.getIndex()); final Iterator<? extends Format> iter = this.formats.iterator(); while (iter.hasNext() && !success) { final Format f = iter.next(); mutateTo(tmpPos, pos); tmpRes = f.parseObject(s, tmpPos); success = tmpPos.getIndex() != pos.getIndex() && tmpPos.getErrorIndex() < 0; } final Object res; if (!success) { // fail with the same as format() res = this.formats.get(this.formatIndex).parseObject(s, pos); } else { res = tmpRes; mutateTo(pos, tmpPos); } return res; }
/* (non-Javadoc) * @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition) */ public Object parseObject(String durationString, ParsePosition pos) { Object result = null; if (durationString.length() == 0) return null; if (durationString.charAt(pos.getIndex()) == '+') // if string begins with + sign, ignore it pos.setIndex(pos.getIndex() + 1); Number numberResult = DECIMAL_FORMAT.parse(durationString, pos); if (numberResult == null) return null; String durationPart = durationString.substring(pos.getIndex()); durationPart = durationPart.trim(); Matcher matcher; for (int i = 0; i < TYPE_COUNT; i++) { // find hte appropriate units matcher = pattern[i].matcher(durationPart); if (matcher.matches()) { int timeUnit = (matcher.group(1) != null) ? i : TimeUnit .NONE; // first group is units. If no units, then it will match, but should use // default: NONE double value = numberResult.doubleValue(); if (timeUnit == TimeUnit.PERCENT || timeUnit == TimeUnit.ELAPSED_PERCENT) value /= 100.0; if (timeUnit == TimeUnit.NONE && isWork) { if (canBeNonTemporal) timeUnit = TimeUnit.NON_TEMPORAL; else timeUnit = ScheduleOption.getInstance() .getWorkUnit(); // use default work unit if work and nothing entered } long longResult = Duration.getInstance(value, timeUnit); if (Duration.millis(longResult) > Duration.MAX_DURATION) // check for too big return null; if (matcher.group(2).length() != 0) { // second group is estimated longResult = Duration.setAsEstimated(longResult, true); } result = new Duration(longResult); return result; } } return null; }
/** * C'tor takes string because a DateLiteral can only be constructed by an implicit cast Parsing * will only succeed if all characters of s are accepted. * * @param s string representation of date * @param type desired type of date literal */ public DateLiteral(String s, PrimitiveType type) throws AnalysisException { Preconditions.checkArgument(type.isDateType()); Date date = null; ParsePosition pos = new ParsePosition(0); for (SimpleDateFormat format : formats) { pos.setIndex(0); date = format.parse(s, pos); if (pos.getIndex() == s.length()) { acceptedFormat = format; break; } } if (acceptedFormat == null) { throw new AnalysisException("Unable to parse string '" + s + "' to date."); } this.value = new Timestamp(date.getTime()); this.type = type; }
private void validateDate(List<String> dateStrings) { SimpleDateFormat formatter = new SimpleDateFormat(this.dateFormat); formatter.setLenient(false); for (String dateString : dateStrings) { try { ParsePosition pos = new ParsePosition(0); formatter.parse(dateString, pos); if (pos.getIndex() != dateString.length()) { throw new ParseException("Could not parse date parameter", pos.getIndex()); } } catch (ParseException pe) { throw new ParameterValidationException( name, i18n.tr("Invalid date string. Expected format: {0}", dateFormat)); } } }
/* (non-Javadoc) * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition) */ @Override public Date parse(final String source, final ParsePosition pos) { final int offset = pos.getIndex(); final Matcher matcher = parsePattern.matcher(source.substring(offset)); if (!matcher.lookingAt()) { return null; } // timing tests indicate getting new instance is 19% faster than cloning final Calendar cal = Calendar.getInstance(timeZone, locale); cal.clear(); for (int i = 0; i < strategies.length; ) { final Strategy strategy = strategies[i++]; strategy.setCalendar(this, cal, matcher.group(i)); } pos.setIndex(offset + matcher.end()); return cal.getTime(); }