List of usage examples for java.text ParsePosition getIndex
public int getIndex()
From source file:net.sf.jabref.model.entry.BibtexEntry.java
/** * Returns the contents of the given field, its alias or null if both are * not set./* w ww . j a v a 2s . c o m*/ * <p> * The following aliases are considered (old bibtex <-> new biblatex) based * on the BibLatex documentation, chapter 2.2.5: * address <-> location * annote <-> annotation * archiveprefix <-> eprinttype * journal <-> journaltitle * key <-> sortkey * pdf <-> file * primaryclass <-> eprintclass * school <-> institution * These work bidirectional. * <p> * Special attention is paid to dates: (see the BibLatex documentation, * chapter 2.3.8) * The fields 'year' and 'month' are used if the 'date' * field is empty. Conversely, getFieldOrAlias("year") also tries to * extract the year from the 'date' field (analogously for 'month'). */ public String getFieldOrAlias(String name) { String fieldValue = getField(name); if (!Strings.isNullOrEmpty(fieldValue)) { return fieldValue; } // No value of this field found, so look at the alias String aliasForField = EntryConverter.FIELD_ALIASES.get(name); if (aliasForField != null) { return getField(aliasForField); } // Finally, handle dates if (name.equals("date")) { String year = getField("year"); MonthUtil.Month month = MonthUtil.getMonth(getField("month")); if (year != null) { if (month.isValid()) { return year + '-' + month.twoDigitNumber; } else { return year; } } } if (name.equals("year") || name.equals("month")) { String date = getField("date"); if (date == null) { return null; } // Create date format matching dates with year and month DateFormat df = new DateFormat() { static final String FORMAT1 = "yyyy-MM-dd"; static final String FORMAT2 = "yyyy-MM"; final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1); final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2); @Override public StringBuffer format(Date dDate, StringBuffer toAppendTo, FieldPosition fieldPosition) { throw new UnsupportedOperationException(); } @Override public Date parse(String source, ParsePosition pos) { if ((source.length() - pos.getIndex()) == FORMAT1.length()) { return sdf1.parse(source, pos); } return sdf2.parse(source, pos); } }; try { Date parsedDate = df.parse(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(parsedDate); if (name.equals("year")) { return Integer.toString(calendar.get(Calendar.YEAR)); } if (name.equals("month")) { return Integer.toString(calendar.get(Calendar.MONTH) + 1); // Shift by 1 since in this calendar Jan = 0 } } catch (ParseException e) { // So not a date with year and month, try just to parse years df = new SimpleDateFormat("yyyy"); try { Date parsedDate = df.parse(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(parsedDate); if (name.equals("year")) { return Integer.toString(calendar.get(Calendar.YEAR)); } } catch (ParseException e2) { LOGGER.warn("Could not parse entry " + name, e2); return null; // Date field not in valid format } } } return null; }
From source file:org.orcid.core.cli.MigrateFundingAmountToANumericValue.java
private BigDecimal getAmountAsBigDecimal(String amount, String currencyCode, Locale locale) throws Exception { try {// ww w . j a v a 2 s . c om ParsePosition parsePosition = new ParsePosition(0); NumberFormat numberFormat = NumberFormat.getInstance(locale); Number number = null; if (!PojoUtil.isEmpty(currencyCode)) { Currency currency = Currency.getInstance(currencyCode); String currencySymbol = currency.getSymbol(); number = numberFormat.parse(amount.replace(currencySymbol, StringUtils.EMPTY), parsePosition); } else { number = numberFormat.parse(amount, parsePosition); } if (parsePosition.getIndex() != amount.length()) throw new Exception("Unable to parse amount into BigDecimal"); return new BigDecimal(number.toString()); } catch (Exception e) { throw e; } }
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 a v a2s . 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:javadz.beanutils.converters.NumberConverter.java
/** * Convert a String into a <code>Number</code> object. * @param sourceType TODO/*from w w w . ja v a2s. co m*/ * @param targetType The type to convert the value to * @param value The String date value. * @param format The NumberFormat to parse the String value. * * @return The converted Number object. * @throws ConversionException if the String cannot be converted. */ private Number parse(Class sourceType, Class targetType, String value, NumberFormat format) { ParsePosition pos = new ParsePosition(0); Number parsedNumber = format.parse(value, pos); if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedNumber == null) { String msg = "Error converting from '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof DecimalFormat) { msg += " using pattern '" + ((DecimalFormat) format).toPattern() + "'"; } if (locale != null) { msg += " for locale=[" + locale + "]"; } if (log().isDebugEnabled()) { log().debug(" " + msg); } throw new ConversionException(msg); } return parsedNumber; }
From source file:HexFormat.java
/** * Parse a hexadecimal number, skipping leading whitespace. Does not throw * an exception; if no object can be parsed, index is unchanged! Hexadecimal * numbers may be indicated with a leading character designation of '0x'. * /*w ww. j ava 2 s.c o m*/ * @param source * the string to parse * @param status * the string index to start at * @return The hexadecimal number as a Long object. * * @since 1.0 */ public Object parseObject(String source, ParsePosition status) { int start = status.getIndex(); boolean success = false; StringBuffer buffer = new StringBuffer(); char c, c2; long result; StringCharacterIterator iter = new StringCharacterIterator(source, start); for (c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) { if (Character.isWhitespace(c)) { // skip whitespace continue; } break; } if (c == CharacterIterator.DONE) { return (null); } if (c == '0') { c2 = iter.next(); if (c2 == CharacterIterator.DONE) { return (null); } if (c2 == 'x') { // has a leading '0x' designation, so skip over it } else { // replace the two characters iter.previous(); iter.previous(); } } else { // skip back one character iter.previous(); } // gather valid hex digits for (c = iter.next(); c != CharacterIterator.DONE; c = iter.next()) { if (hexDigits.indexOf(c) != -1) { success = true; buffer.append(c); } else { break; } } if (!success) { // no valid hex digits return (null); } // convert hex to long if (buffer.length() > 16) { // larger than a long, error // with a buffer full of nibbles, the maximum nibbles in a // 64 bit number is 16 nibbles return (null); } // parse number try { result = Long.parseLong(buffer.toString(), 16); } catch (NumberFormatException e) { // unable to parse number return (null); } status.setIndex(iter.getIndex()); return (new Long(result)); }
From source file:javadz.beanutils.locale.converters.DateLocaleConverter.java
/** * Convert the specified locale-sensitive input object into an output object of the * specified type./* ww w . j a v a 2 s . com*/ * * @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:com.examples.with.different.packagename.testcarver.DateTimeConverter.java
/** * Parse a String into a <code>Calendar</code> object * using the specified <code>DateFormat</code>. * * @param sourceType The type of the value being converted * @param targetType The type to convert the value to * @param value The String date value./*from ww w . j a v a 2 s. com*/ * @param format The DateFormat to parse the String value. * * @return The converted Calendar object. * @throws ConversionException if the String cannot be converted. */ private Calendar parse(Class sourceType, Class targetType, String value, DateFormat format) { logFormat("Parsing", format); format.setLenient(false); ParsePosition pos = new ParsePosition(0); Date parsedDate = format.parse(value, pos); // ignore the result (use the Calendar) if (pos.getErrorIndex() >= 0 || pos.getIndex() != value.length() || parsedDate == null) { String msg = "Error converting '" + toString(sourceType) + "' to '" + toString(targetType) + "'"; if (format instanceof SimpleDateFormat) { msg += " using pattern '" + ((SimpleDateFormat) format).toPattern() + "'"; } throw new ConversionException(msg); } Calendar calendar = format.getCalendar(); return calendar; }
From source file:org.apache.openmeetings.service.calendar.caldav.IcalUtils.java
/** * Adapted from DateUtils to support Timezones, and parse ical dates into {@link java.util.Date}. * Note: Replace FastDateFormat to java.time, when shifting to Java 8 or higher. * * @param str Date representation in String. * @param patterns Patterns to parse the date against * @param _timeZone Timezone of the Date. * @return <code>java.util.Date</code> representation of string or * <code>null</code> if the Date could not be parsed. *//* ww w .j av a 2s . co m*/ public Date parseDate(String str, String[] patterns, TimeZone _timeZone) { FastDateFormat parser; Locale locale = WebSession.get().getLocale(); TimeZone timeZone = str.endsWith("Z") ? TimeZone.getTimeZone("UTC") : _timeZone; ParsePosition pos = new ParsePosition(0); for (String pattern : patterns) { parser = FastDateFormat.getInstance(pattern, timeZone, locale); pos.setIndex(0); Date date = parser.parse(str, pos); if (date != null && pos.getIndex() == str.length()) { return date; } } log.error("Unable to parse the date: " + str + " at " + -1); return null; }
From source file:Unsigned.java
/** * Parse a binary number into a Number object. If up to 8 bits are parsed, * returns a Byte. If more than 8 and up to 16 bits are parsed, return a * Short. If more than 16 and up to 32 bits are parsed, return an Integer. * If more than 32 and up to 64 bits are parsed, return a Long. * // w w w . j a v a2 s . c om * @param text * a binary number * @param parsePosition * position to start parsing from * @return return an integer form of Number object if parse is successful; * <CODE>null</CODE> otherwise * * @since 1.0 */ public Number parse(String text, ParsePosition parsePosition) { boolean skipWhitespace = true; int startIndex, bits; // remove whitespace StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex()); for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) { if (skipWhitespace && Character.isWhitespace(c)) { // skip whitespace continue; } } parsePosition.setIndex(iter.getIndex()); startIndex = parsePosition.getIndex(); Number result = (Number) parseObject(text, parsePosition); if (result == null) { return (result); } bits = parsePosition.getIndex() - startIndex; if (bits <= 8) { result = new Byte(result.byteValue()); } else if (bits <= 16) { result = new Short(result.shortValue()); } else if (bits <= 32) { result = new Integer(result.intValue()); } else if (bits <= 64) { result = new Long(result.longValue()); } return (result); }
From source file:Unsigned.java
/** * Parse a binary number into a Number object. If up to 8 bits are parsed, * returns a Byte. If more than 8 and up to 16 bits are parsed, return a * Short. If more than 16 and up to 32 bits are parsed, return an Integer. * If more than 32 and up to 64 bits are parsed, return a Long. * /*from www . ja va2 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 BinaryFormat", parsePosition.getIndex()); } return (result); }