List of usage examples for java.text ParsePosition ParsePosition
public ParsePosition(int index)
From source file:org.kuali.rice.core.impl.datetime.DateTimeServiceImpl.java
protected Date parse(String dateString, String pattern) throws ParseException { if (!StringUtils.isBlank(dateString)) { DateFormat dateFormat = new SimpleDateFormat(pattern); dateFormat.setLenient(false);//from w w w . java2 s .c om ParsePosition parsePosition = new ParsePosition(0); Date testDate = dateFormat.parse(dateString, parsePosition); // Ensure that the entire date String can be parsed by the current format. if (testDate == null) { throw new ParseException("The date that you provided is invalid.", parsePosition.getErrorIndex()); } else if (parsePosition.getIndex() != dateString.length()) { throw new ParseException("The date that you provided is invalid.", parsePosition.getIndex()); } // Ensure that the date's year lies between 1000 and 9999, to help prevent database-related date errors. Calendar testCalendar = Calendar.getInstance(); testCalendar.setLenient(false); testCalendar.setTime(testDate); if (testCalendar.get(Calendar.YEAR) < 1000 || testCalendar.get(Calendar.YEAR) > 9999) { throw new ParseException("The date that you provided is not between the years 1000 and 9999.", -1); } if (testCalendar.get(Calendar.YEAR) == 1970 && !pattern.contains("y".toLowerCase())) { Calendar curCalendar = Calendar.getInstance(); curCalendar.setTime(new java.util.Date()); testCalendar.set(Calendar.YEAR, curCalendar.get(Calendar.YEAR)); testDate = testCalendar.getTime(); } return testDate; } return null; }
From source file:org.noorganization.instalistsynch.controller.synch.impl.UnitSynch.java
@Override public void indexLocal(int _groupId, Date _lastIndexTime) { String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000")); Cursor changeLog = mLocalLogController.getLogsSince(lastIndexTime, eModelType.UNIT); while (changeLog.moveToNext()) { int actionId = changeLog.getInt(changeLog.getColumnIndex(LogInfo.COLUMN.ACTION)); eActionType actionType = eActionType.getTypeById(actionId); String uuid = changeLog.getString(changeLog.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)); if (uuid.contentEquals("-")) continue; List<ModelMapping> existingMappings = mMappingController.get( ModelMapping.COLUMN.CLIENT_SIDE_UUID + " = ? AND " + ModelMapping.COLUMN.GROUP_ID + " = ?", new String[] { uuid, String.valueOf(_groupId) }); ModelMapping existingMapping = (existingMappings.size() == 0 ? null : existingMappings.get(0)); if (actionType == null) { Log.w(TAG, "Changelog contains entry without action."); continue; }//from www . ja v a 2s . c o m switch (actionType) { case INSERT: { if (existingMapping == null) { ModelMapping newMapping = new ModelMapping(null, _groupId, null, uuid, new Date(Constants.INITIAL_DATE), new Date(), false); mMappingController.insert(newMapping); } break; } case UPDATE: { if (existingMapping == null) { Log.e(TAG, "Changelog contains update, but mapping does not exist. " + "Ignoring."); continue; } try { Date clientDate = ISO8601Utils.parse( changeLog.getString(changeLog.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); existingMapping.setLastClientChange(clientDate); mMappingController.update(existingMapping); } catch (ParseException e) { Log.e(TAG, "Change log contains invalid date: " + e.getMessage()); continue; } break; } case DELETE: { if (existingMapping == null) { Log.e(TAG, "Changelog contains deletion, but mapping does not exist. " + "Ignoring."); continue; } try { Date clientDate = ISO8601Utils.parse( changeLog.getString(changeLog.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); existingMapping.setLastClientChange(clientDate); existingMapping.setDeleted(true); mMappingController.update(existingMapping); } catch (ParseException e) { Log.e(TAG, "Change log contains invalid date: " + e.getMessage()); continue; } break; } } } changeLog.close(); }
From source file:com.jeeframework.util.validate.GenericTypeValidator.java
/** * Checks if the value can safely be converted to a double primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null)/*from w w w .j a va 2s . com*/ *@return the converted Double value. */ public static Double formatDouble(String value, Locale locale) { Double result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getInstance(locale); } else { formatter = NumberFormat.getInstance(Locale.getDefault()); } 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()) { if (num.doubleValue() >= (Double.MAX_VALUE * -1) && num.doubleValue() <= Double.MAX_VALUE) { result = new Double(num.doubleValue()); } } } return result; }
From source file:org.opendatakit.common.utils.WebUtils.java
/** * Parse a string into a datetime value. Tries the common Http formats, the * iso8601 format (used by Javarosa), the default formatting from * Date.toString(), and a time-only format. * * @param value/* w w w . ja v a2 s .c o m*/ * @return */ public static final Date parseDate(String value) { if (value == null || value.length() == 0) return null; String[] iso8601Pattern = new String[] { PATTERN_ISO8601 }; String[] localizedParsePatterns = new String[] { // try the common HTTP date formats that have time zones PATTERN_RFC1123, PATTERN_RFC1036, PATTERN_DATE_TOSTRING }; String[] localizedNoTzParsePatterns = new String[] { // ones without timezones... (will assume UTC) PATTERN_ASCTIME }; String[] tzParsePatterns = new String[] { PATTERN_ISO8601, PATTERN_ISO8601_DATE, PATTERN_ISO8601_TIME }; String[] noTzParsePatterns = new String[] { // ones without timezones... (will assume UTC) PATTERN_ISO8601_WITHOUT_ZONE, PATTERN_NO_DATE_TIME_ONLY, PATTERN_YYYY_MM_DD_DATE_ONLY_NO_TIME_DASH, PATTERN_GOOGLE_DOCS }; Date d = null; // iso8601 parsing is sometimes off-by-one when JR does it... d = parseDateSubset(value, iso8601Pattern, null, TimeZone.getTimeZone("GMT")); if (d != null) return d; // try to parse with the JavaRosa parsers d = DateUtils.parseDateTime(value); if (d != null) return d; d = DateUtils.parseDate(value); if (d != null) return d; d = DateUtils.parseTime(value); if (d != null) return d; // try localized and english text parsers (for Web headers and interactive // filter spec.) d = parseDateSubset(value, localizedParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT")); if (d != null) return d; d = parseDateSubset(value, localizedParsePatterns, null, TimeZone.getTimeZone("GMT")); if (d != null) return d; d = parseDateSubset(value, localizedNoTzParsePatterns, Locale.ENGLISH, TimeZone.getTimeZone("GMT")); if (d != null) return d; d = parseDateSubset(value, localizedNoTzParsePatterns, null, TimeZone.getTimeZone("GMT")); if (d != null) return d; // try other common patterns that might not quite match JavaRosa parsers d = parseDateSubset(value, tzParsePatterns, null, TimeZone.getTimeZone("GMT")); if (d != null) return d; d = parseDateSubset(value, noTzParsePatterns, null, TimeZone.getTimeZone("GMT")); if (d != null) return d; // try the locale- and timezone- specific parsers { DateFormat formatter = DateFormat.getDateTimeInstance(); ParsePosition pos = new ParsePosition(0); d = formatter.parse(value, pos); if (d != null && pos.getIndex() == value.length()) { return d; } } { DateFormat formatter = DateFormat.getDateInstance(); ParsePosition pos = new ParsePosition(0); d = formatter.parse(value, pos); if (d != null && pos.getIndex() == value.length()) { return d; } } { DateFormat formatter = DateFormat.getTimeInstance(); ParsePosition pos = new ParsePosition(0); d = formatter.parse(value, pos); if (d != null && pos.getIndex() == value.length()) { return d; } } throw new IllegalArgumentException("Unable to parse the date: " + value); }
From source file:javadz.beanutils.locale.converters.DateLocaleConverter.java
/** * Convert the specified locale-sensitive input object into an output object of the * specified type.//from w ww. ja v a 2s . co m * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * @return the converted Date value * * @exception org.apache.commons.beanutils.ConversionException * if conversion cannot be performed successfully * @throws ParseException if an error occurs parsing */ protected Object parse(Object value, String pattern) throws ParseException { // Handle Date if (value instanceof java.util.Date) { return value; } // Handle Calendar if (value instanceof java.util.Calendar) { return ((java.util.Calendar) value).getTime(); } if (locPattern) { pattern = convertLocalizedPattern(pattern, locale); } // Create Formatter - use default if pattern is null DateFormat formatter = pattern == null ? DateFormat.getDateInstance(DateFormat.SHORT, locale) : new SimpleDateFormat(pattern, locale); formatter.setLenient(isLenient); // Parse the Date ParsePosition pos = new ParsePosition(0); String strValue = value.toString(); Object parsedValue = formatter.parseObject(strValue, pos); if (pos.getErrorIndex() > -1) { throw new ConversionException("Error parsing date '" + value + "' at position=" + pos.getErrorIndex()); } if (pos.getIndex() < strValue.length()) { throw new ConversionException( "Date '" + value + "' contains unparsed characters from position=" + pos.getIndex()); } return parsedValue; }
From source file:org.totschnig.myexpenses.util.Utils.java
/** * <a href="http://www.ibm.com/developerworks/java/library/j-numberformat/"> * http://www.ibm.com/developerworks/java/library/j-numberformat/</a> * * @param strFloat//from w ww. j av a 2 s. c o m * parsed as float with the number format defined in the locale * @return the float retrieved from the string or null if parse did not * succeed */ public static BigDecimal validateNumber(DecimalFormat df, String strFloat) { ParsePosition pp; pp = new ParsePosition(0); pp.setIndex(0); df.setParseBigDecimal(true); BigDecimal n = (BigDecimal) df.parse(strFloat, pp); if (strFloat.length() != pp.getIndex() || n == null) { return null; } else { return n; } }
From source file:HexFormat.java
/** * Parse a hex number into a Number object. Hexadecimal numbers may be * indicated with a leading character designation of '0x'. If up to 1 byte * is parsed, returns a Byte. If more than 1 and up to 2 bytes are parsed, * return a Short. If more than 2 and up to 4 bytes are parsed, return an * Integer. If more than 4 and up to 8 bytes are parsed, return a Long. * // w w w.j av a2 s .c o m * @param source * a binary number * @return return an integer form of Number object if parse is successful * @exception ParseException * thrown if source is cannot be converted to a Byte, Short, * Int, or Long. * * @since 1.0 */ public Number parse(String source) throws ParseException { int startIndex = 0; Number result; ParsePosition parsePosition = new ParsePosition(startIndex); result = parse(source, parsePosition); if (result == null) { throw new ParseException("Unable to parse " + source + " using HexFormat", parsePosition.getIndex()); } return (result); }
From source file:net.sf.farrago.namespace.sfdc.SfdcUdx.java
public static void getDeleted(String objectName, String start, String end, PreparedStatement resultInserter) throws SQLException { SoapBindingStub binding = (SoapBindingStub) FarragoUdrRuntime.getDataServerRuntimeSupport(null); if (((start == null) || start.equals("")) || ((end == null) || end.equals(""))) { throw SfdcResource.instance().InvalidRangeException.ex(); }/*from www . j a va 2 s . c om*/ Calendar startTime; Calendar endTime; Calendar thirtyDaysAgo; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); java.util.Date sd = sdf.parse(start, new ParsePosition(0)); startTime = Calendar.getInstance(); startTime.setTime(sd); java.util.Date now = new java.util.Date(); // 30 days == 30*24*60*60*1000 ms Long thirty = new Long("2592000000"); java.util.Date thirtyDate = new java.util.Date(now.getTime() - thirty.longValue()); thirtyDaysAgo = Calendar.getInstance(); thirtyDaysAgo.setTime(thirtyDate); java.util.Date ed = sdf.parse(end, new ParsePosition(0)); endTime = Calendar.getInstance(); endTime.setTime(ed); } catch (Exception ex) { ex.printStackTrace(); throw SfdcResource.instance().InvalidTimeException.ex(ex.getMessage()); } if (thirtyDaysAgo.compareTo(startTime) > 0) { throw SfdcResource.instance().InvalidStartTimeException.ex(startTime.getTime().toString()); } if (startTime.compareTo(endTime) > 0) { throw SfdcResource.instance().InvalidEndTimeException.ex(endTime.getTime().toString(), startTime.getTime().toString()); } SfdcDataServer server = (SfdcDataServer) FarragoUdrRuntime.getDataServerRuntimeSupport(new Object()); try { DescribeSObjectResult describeSObjectResult = (DescribeSObjectResult) server .getEntityDescribe(objectName); // check the name if ((describeSObjectResult != null) && describeSObjectResult.getName().equals(objectName)) { // check if data replication is allowed on object if (!describeSObjectResult.isReplicateable()) { throw SfdcResource.instance().ReplicationException.ex(objectName); } } else { throw SfdcResource.instance().InvalidObjectException.ex(objectName); } GetDeletedResult gdr = binding.getDeleted(objectName, startTime, endTime); if ((gdr.getDeletedRecords() != null) && (gdr.getDeletedRecords().length > 0)) { for (int i = 0; i < gdr.getDeletedRecords().length; i++) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); StringBuffer sbuf = new StringBuffer(); String idString = gdr.getDeletedRecords(i).getId(); int prec = 25 + server.getVarcharPrecision(); if (idString.length() > prec) { idString = idString.substring(0, prec); } resultInserter.setString(1, idString); String timeStr = sdf .format(gdr.getDeletedRecords(i).getDeletedDate().getTime(), sbuf, new FieldPosition(0)) .toString(); resultInserter.setTimestamp(2, java.sql.Timestamp.valueOf(timeStr)); resultInserter.executeUpdate(); } } } catch (AxisFault ae) { SQLException retryExcn = new SQLException(ae.getFaultString(), null, 460150); Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn); throw SfdcResource.instance().BindingCallException.ex(ae.getFaultString(), chainedEx); } catch (RemoteException re) { SQLException retryExcn = new SQLException(re.getMessage(), null, 460150); Exception chainedEx = FarragoResource.instance().RetryableFailure.ex(retryExcn); throw SfdcResource.instance().BindingCallException.ex(re.getMessage(), chainedEx); } }
From source file:routines.system.BigDataParserUtils.java
public synchronized static java.util.Date parseTo_Date(String s, String pattern) { if (isBlank(s)) { return null; }//from w ww . j a va 2s . c om String s2 = s.trim(); String pattern2 = pattern; if (isBlank(pattern2)) { pattern2 = Constant.dateDefaultPattern; } java.util.Date date = null; if (pattern2.equals("yyyy-MM-dd'T'HH:mm:ss'000Z'")) { if (!s2.endsWith("000Z")) { throw new RuntimeException("Unparseable date: \"" + s2 + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } pattern2 = "yyyy-MM-dd'T'HH:mm:ss"; s2 = s.substring(0, s.lastIndexOf("000Z")); } DateFormat format = FastDateParser.getInstance(pattern2); ParsePosition pp = new ParsePosition(0); pp.setIndex(0); format.setTimeZone(TimeZone.getTimeZone("UTC")); date = format.parse(s2, pp); if (pp.getIndex() != s2.length() || date == null) { throw new RuntimeException("Unparseable date: \"" + s2 + "\""); //$NON-NLS-1$ //$NON-NLS-2$ } return date; }
From source file:com.application.utils.FastDateParser.java
@Override public Date parse(final String source) throws ParseException { final Date date = parse(source, new ParsePosition(0)); if (date == null) { // Add a note re supported date range if (locale.equals(JAPANESE_IMPERIAL)) { throw new ParseException( "(The " + locale + " locale does not support dates before 1868 AD)\n" + "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0);// w ww .j ava2s.c o m } throw new ParseException( "Unparseable date: \"" + source + "\" does not match " + parsePattern.pattern(), 0); } return date; }