Example usage for java.text ParsePosition ParsePosition

List of usage examples for java.text ParsePosition ParsePosition

Introduction

In this page you can find the example usage for java.text ParsePosition ParsePosition.

Prototype

public ParsePosition(int index) 

Source Link

Document

Create a new ParsePosition with the given initial index.

Usage

From source file:javadz.beanutils.converters.NumberConverter.java

/**
 * Convert a String into a <code>Number</code> object.
 * @param sourceType TODO//from  w ww.  j a va 2 s . 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: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./*ww  w  .  ja va  2s.c  o  m*/
 * @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:javadz.beanutils.converters.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 w w w.j  ava2 s . c  o m
 * @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() + "'";
        }
        if (log().isDebugEnabled()) {
            log().debug("    " + msg);
        }
        throw new ConversionException(msg);
    }
    Calendar calendar = format.getCalendar();
    return calendar;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Decode an XML Schema date data type (YYYY-MM-DD) to a Java Date object.
 * /* www .  j  a v a 2  s.  co m*/
 * @param aDateValue
 *            XML Schema date data type string (YYYY-MM-DD).
 * @return Java Date object.
 */
public static Date decodeDate(String aDateValue) {

    SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

    // Set to UTC with no time element
    Calendar theCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    theCal.set(Calendar.HOUR_OF_DAY, 0);
    theCal.set(Calendar.MINUTE, 0);
    theCal.set(Calendar.SECOND, 0);
    theCal.set(Calendar.MILLISECOND, 0);
    formatter.setCalendar(theCal);

    Date theDate = formatter.parse(aDateValue, new ParsePosition(0));

    return theDate;
}

From source file:edu.hawaii.soest.hioos.storx.StorXParser.java

/**
 * Parses the binary STOR-X timestamp. The timestamp format is
 * YYYYDDD from the first 3 bytes, and HHMMSS.SSS from the last four:
 * Example://from   ww  w  .j a  v a 2s  . c o  m
 * 1E AC CC = 2010316 (year 2010, julian day 316)
 * 09 9D 3E 20 = 16:13:00.000 (4:13 pm)
 * @param timestamp - the timestamp to parse as a byte array
 * @return date - the timestamp as a Date object
 */
public Date parseTimestamp(byte[] timestamp) {

    Date convertedDate = new Date(0L); // initialize to the epoch

    try {
        ByteBuffer timestampBuffer = ByteBuffer.wrap(timestamp);

        // convert the year and day bytes
        int yearAndJulianDay = ((timestampBuffer.get() & 0xFF) << 16) | ((timestampBuffer.get() & 0xFF) << 8)
                | ((timestampBuffer.get() & 0xFF));

        String yearAndJulianDayString = new Integer(yearAndJulianDay).toString();

        // convert the hour, minute, second, millis bytes
        int hourMinuteSecondMillis = timestampBuffer.getInt();
        String hourMinuteSecondMillisString = String.format("%09d", hourMinuteSecondMillis);

        // concatenate the strings to get the timestamp
        String timestampString = yearAndJulianDayString + hourMinuteSecondMillisString;

        // convert to a Date object
        FRAME_DATE_FORMAT.setTimeZone(TZ);
        convertedDate = FRAME_DATE_FORMAT.parse(timestampString, new ParsePosition(0));

    } catch (BufferUnderflowException bue) {

        logger.debug(
                "There was a problem reading the timestamp. " + "The error message was: " + bue.getMessage());

    } catch (NullPointerException npe) {

        logger.debug("There was a problem converting the timestamp. " + "The error message was: "
                + npe.getMessage());

    } finally {

        return convertedDate;

    }

}

From source file:adalid.commons.util.TimeUtils.java

public static java.util.Date parse(String pdq) {
    if (StringUtils.isBlank(pdq)) {
        return null;
    }/*from   w  ww.  j a va 2 s .co  m*/
    String string = pdq.trim();
    ParsePosition position = new ParsePosition(0);
    java.util.Date util = timestampFormatter().parse(string, position);
    int i = position.getIndex();
    int l = string.length();
    if (util != null && i == l) {
        return new Timestamp(util.getTime());
    }
    position.setIndex(0);
    util = dateFormatter().parse(string, position);
    i = position.getIndex();
    if (util != null) {
        if (i == l) {
            return new Date(util.getTime());
        }
        java.util.Date time = timeFormatter().parse(string, position);
        i = position.getIndex();
        if (time != null && i == l) {
            return merge(util, time);
        }
    }
    position.setIndex(0);
    util = timeFormatter().parse(string, position);
    i = position.getIndex();
    if (util != null && i == l) {
        return new Time(util.getTime());
    }
    return null;
}

From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java

/**
 * Translate a data row according to the currently defined schema.
 * //from  w  ww.j a  va 2  s. c  om
 * @param dataRow cells containing data
 * @return an array of objects of primitive datatypes (boolean, int, byte, etc.)
 *         containing the data of datarow, null if dataRow does not fit into
 *         schema. Note: single elements can be null depending on the original
 *         Excel
 * 
 */
public Object[] getDataAccordingToSchema(SpreadSheetCellDAO[] dataRow) {
    if (dataRow == null) {
        return new Object[this.schemaRow.size()];
    }
    if (dataRow.length > this.schemaRow.size()) {
        LOG.warn("Data row is larger than schema. Will return String for everything that is not specified. ");
    }
    List<Object> returnList = new ArrayList<>();
    for (int i = 0; i < this.schemaRow.size(); i++) { // fill up with schema rows
        returnList.add(null);
    }
    for (int i = 0; i < dataRow.length; i++) {
        SpreadSheetCellDAO currentCell = dataRow[i];

        if (currentCell != null) {
            // determine real position
            int j = new CellAddress(currentCell.getAddress()).getColumn();
            if (j >= returnList.size()) {
                // fill up
                for (int x = returnList.size(); x <= j; x++) {
                    returnList.add(null);
                }
            }
            GenericDataType applyDataType = null;
            if (j >= this.schemaRow.size()) {
                LOG.warn("No further schema row for column defined: " + String.valueOf(j)
                        + ". Will assume String.");
            } else {
                applyDataType = this.schemaRow.get(j);
            }
            if (applyDataType == null) {
                returnList.set(j, currentCell.getFormattedValue());
            } else if (applyDataType instanceof GenericStringDataType) {
                returnList.set(j, currentCell.getFormattedValue());
            } else if (applyDataType instanceof GenericBooleanDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    if (currentCell.getFormattedValue().equalsIgnoreCase("true")
                            || currentCell.getFormattedValue().equalsIgnoreCase("false")) {
                        returnList.set(j, Boolean.valueOf(currentCell.getFormattedValue()));
                    }
                }
            } else if (applyDataType instanceof GenericTimestampDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    boolean timestampFound = false;
                    if (this.dateTimeFormat != null) { // check first dateTimeFormat
                        Date theDate = this.dateTimeFormat.parse(currentCell.getFormattedValue(),
                                new ParsePosition(0));
                        if (theDate != null) {
                            returnList.set(j, new java.sql.Timestamp(theDate.getTime()));
                            timestampFound = true;
                        } else {
                            returnList.set(j, null);
                            LOG.warn(
                                    "Could not identify timestamp using Date.parse using provided dateTime format. Trying Timestamp.valueOf. Original value: "
                                            + currentCell.getFormattedValue());
                        }
                    }
                    if (!timestampFound) {
                        try {
                            returnList.set(j, java.sql.Timestamp.valueOf(currentCell.getFormattedValue()));
                            timestampFound = true;
                        } catch (IllegalArgumentException e) {
                            returnList.set(j, null);
                            LOG.warn(
                                    "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing. Original value: "
                                            + currentCell.getFormattedValue());
                        }
                    }
                    if (!timestampFound) {
                        Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(),
                                new ParsePosition(0));
                        if (theDate != null) {
                            returnList.set(j, new java.sql.Timestamp(theDate.getTime()));

                        } else {
                            returnList.set(j, null);
                            LOG.warn(
                                    "Could not identify timestamp using Date.parse using provided date format");
                        }
                    }

                }
            } else if (applyDataType instanceof GenericDateDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0));

                    if (theDate != null) {
                        returnList.set(j, theDate);

                    } else {
                        returnList.set(j, null);
                    }
                }
            }

            else if (applyDataType instanceof GenericNumericDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    BigDecimal bd = null;
                    try {
                        if (!"".equals(currentCell.getFormattedValue())) {
                            // check scientific notation
                            if (currentCell.getFormattedValue().toUpperCase().contains("E")) { // parse scientific notation
                                // remove any characters that could cause issues
                                String sanitizedCellContent = currentCell.getFormattedValue().replace(",", ".");
                                bd = new BigDecimal(sanitizedCellContent);
                            } else {
                                bd = (BigDecimal) this.decimalFormat.parse(currentCell.getFormattedValue());
                            }
                        }
                    } catch (ParseException p) {
                        LOG.warn(
                                "Could not parse decimal in spreadsheet cell, although type was detected as decimal");
                    }
                    if (bd != null) {
                        BigDecimal bdv = bd.stripTrailingZeros();
                        if (applyDataType instanceof GenericByteDataType) {
                            returnList.set(j, (byte) bdv.byteValueExact());
                        } else if (applyDataType instanceof GenericShortDataType) {
                            returnList.set(j, (short) bdv.shortValueExact());
                        } else if (applyDataType instanceof GenericIntegerDataType) {
                            returnList.set(j, (int) bdv.intValueExact());
                        } else if (applyDataType instanceof GenericLongDataType) {
                            returnList.set(j, (long) bdv.longValueExact());
                        } else if (applyDataType instanceof GenericDoubleDataType) {
                            returnList.set(j, (double) bdv.doubleValue());
                        } else if (applyDataType instanceof GenericFloatDataType) {
                            returnList.set(j, (float) bdv.floatValue());
                        } else if (applyDataType instanceof GenericBigDecimalDataType) {
                            returnList.set(j, bd);
                        } else {
                            returnList.set(j, null);
                        }
                    }
                }
            } else {
                returnList.set(j, null);
                LOG.warn("Could not convert object in spreadsheet cellrow. Did you add a new datatype?");
            }
        }
    }
    Object[] result = new Object[returnList.size()];
    returnList.toArray(result);
    return result;
}

From source file:com.flexive.shared.FxFormatUtils.java

/**
 * Convert a String to Integer//from  w ww  .  j a  v a  2  s  .  c o  m
 *
 * @param value value to convert
 * @return Integer
 */
public static Integer toInteger(String value) {
    if (StringUtils.isBlank(value))
        return null;
    final ParsePosition pos = new ParsePosition(0);
    final String _value = value.trim();
    try {
        final Number parse = FxValueRendererFactory.getNumberFormatInstance().parse(unquote(_value), pos);
        if (pos.getErrorIndex() >= 0 || pos.getIndex() != _value.length()
                || parse.doubleValue() != (double) parse.intValue() /*truncation*/)
            throw new FxConversionException("ex.conversion.value.error", FxNumber.class.getCanonicalName(),
                    value, "Failed to parse " + value).asRuntimeException();
        return parse.intValue();
    } catch (NumberFormatException e) {
        throw new FxConversionException("ex.conversion.value.error", FxLargeNumber.class.getCanonicalName(),
                value,
                "Failed to parse [" + value + "] using dec.sep. [" + FxContext.get().getDecimalSeparator()
                        + "] and grouping sep. [" + FxContext.get().getDecimalSeparator() + "]")
                                .asRuntimeException();
    }
}

From source file:com.nridge.core.base.field.Field.java

/**
 * Returns a <i>Date</i> representation of the field value
 * string based on the format mask property.
 *
 * @param aValue Date/Time string value.
 * @param aFormatMask SimpleDateFormat mask.
 *
 * @return Converted value./*from w  ww.  j a va  2s . com*/
 */
public static Date createDate(String aValue, String aFormatMask) {
    if (StringUtils.isNotEmpty(aValue)) {
        ParsePosition parsePosition = new ParsePosition(0);
        SimpleDateFormat simpleDateFormat;
        if (StringUtils.isNotEmpty(aFormatMask))
            simpleDateFormat = new SimpleDateFormat(aFormatMask);
        else
            simpleDateFormat = new SimpleDateFormat(Field.FORMAT_DATETIME_DEFAULT);
        return simpleDateFormat.parse(aValue, parsePosition);
    } else
        return new Date();
}

From source file:saschpe.birthdays.service.CalendarSyncService.java

private static Date parseEventDateString(String eventDateString) {
    if (eventDateString != null) {
        Date eventDate = null;/*from www .  ja  v  a  2 s .  c  om*/

        for (String dateFormat : DATE_FORMATS) {
            if (eventDate == null) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
                simpleDateFormat.setTimeZone(TimeZone.getDefault());

                eventDate = simpleDateFormat.parse(eventDateString, new ParsePosition(0));
                if (eventDate != null && !dateFormat.contains("yyyy")) {
                    // Because no year is defined in address book, set year to 1700. When
                    // year < 1800, the age will be not displayed in brackets
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(eventDate);
                    cal.set(Calendar.YEAR, 1700);
                }
            }
        }
        // Unix timestamp - Some Motorola devices
        if (eventDate == null) {
            try {
                eventDate = new Date(Long.parseLong(eventDateString));
            } catch (NumberFormatException e) {
                Log.e(TAG, "Error parsing event date string " + eventDateString);
            }
        }
        /*if (eventDate != null) {
        Log.debug("Parsed event date string: " + eventDate.toString());
        }*/
        return eventDate;
    } else {
        return null;
    }
}