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: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.
 *//*  www. j av a2 s.  c  om*/
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:de.betterform.xml.xforms.ui.AbstractFormControl.java

private BigDecimal strictParse(String value, Locale locale) throws ParseException {
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
    format.setParseBigDecimal(true);/*from   w w w .ja v a2s.  c om*/
    value = value.trim();
    ParsePosition pos = new ParsePosition(0);
    BigDecimal number = (BigDecimal) format.parse(value, pos);
    boolean okay = pos.getIndex() == value.length() && pos.getErrorIndex() == -1;
    if (!okay)
        throw new ParseException("Could not parse '" + value + "' as a number", pos.getErrorIndex());
    return number;
}

From source file:org.kepler.io.DirectoryListing.java

private long getUTC(String date_, String time_) {
    String dateStr = date_ + " " + time_;
    ParsePosition pp = new ParsePosition(0);
    Date d = sdf2.parse(dateStr, pp);
    //System.out.println("getUTC: Parsed " + dateStr + " to " + d);
    long utc = d.getTime() / 1000;
    return utc;/*w  w w.ja va  2s .  c  om*/
}

From source file:org.mule.modules.clarizen.api.ClarizenDateConverter.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  ww . ja v a 2 s .  co  m
 * @param format The DateFormat to parse the String value.
 *
 * @return The converted Calendar object.
 * @throws ConversionException if the String cannot be converted.
 */
@SuppressWarnings("rawtypes")
private Calendar parse(Class sourceType, Class targetType, String value, DateFormat 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 '" + classToString(sourceType) + "' to '" + classToString(targetType)
                + "'";
        if (format instanceof SimpleDateFormat) {
            msg += " using pattern '" + ((SimpleDateFormat) format).toPattern() + "'";
        }
        throw new ConversionException(msg);
    }
    Calendar calendar = format.getCalendar();
    return calendar;
}

From source file:com.glaf.core.util.DateUtils.java

public static Date parseDate(String str, String[] parsePatterns) {
    if (str == null || parsePatterns == null) {
        throw new IllegalArgumentException("Date and Patterns must not be null");
    }//  w w  w .  j  a  v  a 2s. c om
    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(str, pos);
        if (date != null && pos.getIndex() == str.length()) {
            return date;
        }
    }
    throw new RuntimeException("Unable to parse the date: " + str);
}

From source file:org.apache.ambari.scom.SQLPropertyProvider.java

private Map<MetricDefinition, List<DataPoint>> getMetric(Set<MetricDefinition> metricDefinitionSet,
        Statement statement) throws SystemException {
    Map<MetricDefinition, List<DataPoint>> results = new HashMap<MetricDefinition, List<DataPoint>>();
    try {/*from   w  w  w .ja  va  2 s  .  c o  m*/
        StringBuilder query = new StringBuilder();
        Set<String> recordTypeContexts = new HashSet<String>();
        Set<String> recordTypeNamess = new HashSet<String>();
        Set<String> tagPairsPatterns = new HashSet<String>();
        Set<String> nodeNames = new HashSet<String>();
        Set<String> serviceNames = new HashSet<String>();
        Set<String> metricNames = new HashSet<String>();
        long startTime = 0, endTime = 0;
        for (MetricDefinition metricDefinition : metricDefinitionSet) {
            if (metricDefinition.getRecordTypeContext() == null || metricDefinition.getRecordTypeName() == null
                    || metricDefinition.getNodeName() == null) {
                continue;
            }

            recordTypeContexts.add(metricDefinition.getRecordTypeContext());
            recordTypeNamess.add(metricDefinition.getRecordTypeName());
            tagPairsPatterns.add(metricDefinition.getTagPairsPattern());
            nodeNames.add(metricDefinition.getNodeName());
            serviceNames.add(metricDefinition.getServiceName());
            metricNames.add(metricDefinition.getMetricName());
            startTime = metricDefinition.getStartTime();
            endTime = metricDefinition.getEndTime();
        }

        for (String tagPairsPattern : tagPairsPatterns) {
            if (query.length() != 0) {
                query.append("\nUNION\n");
            }
            query.append(String.format(GET_METRICS_STATEMENT,
                    "'" + StringUtils.join(recordTypeContexts, "','") + "'",
                    "'" + StringUtils.join(recordTypeNamess, "','") + "'", "'%" + tagPairsPattern + "%'",
                    "'" + StringUtils.join(nodeNames, "','") + "'",
                    "'" + StringUtils.join(serviceNames, "','") + "'", startTime, endTime,
                    "'" + StringUtils.join(metricNames, "','") + "'"));
        }

        ResultSet rs = null;
        if (query.length() != 0) {
            rs = statement.executeQuery(query.toString());
        }

        if (rs != null) {
            //(RecordTimeStamp bigint, MetricValue NVARCHAR(512))
            while (rs.next()) {
                MetricDefinition metricDefinition = new MetricDefinition(rs.getString("RecordTypeContext"),
                        rs.getString("RecordTypeName"), rs.getString("TagPairs"), rs.getString("MetricName"),
                        rs.getString("ServiceName"), rs.getString("NodeName"));
                ParsePosition parsePosition = new ParsePosition(0);
                NumberFormat numberFormat = NumberFormat.getInstance();
                Number parsedNumber = numberFormat.parse(rs.getNString("MetricValue"), parsePosition);
                if (results.containsKey(metricDefinition)) {
                    results.get(metricDefinition)
                            .add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
                } else {
                    List<DataPoint> dataPoints = new ArrayList<DataPoint>();
                    dataPoints.add(new DataPoint(rs.getLong("RecordTimeStamp"), parsedNumber));
                    results.put(metricDefinition, dataPoints);
                }
            }
        }
    } catch (SQLException e) {
        throw new SystemException("Error during getMetric call : caught exception - ", e);
    }
    return results;
}

From source file:org.apache.roller.util.DateUtil.java

/**
 * Parse data as either 6-char or 8-char format.
 */// www.  j a  va  2  s  .c  o m
public static Date parseWeblogURLDateString(String dateString, TimeZone tz, Locale locale) {

    Date ret = new Date();
    SimpleDateFormat char8DateFormat = DateUtil.get8charDateFormat();
    SimpleDateFormat char6DateFormat = DateUtil.get6charDateFormat();

    if (dateString != null && dateString.length() == 8 && StringUtils.isNumeric(dateString)) {
        ParsePosition pos = new ParsePosition(0);
        ret = char8DateFormat.parse(dateString, pos);

        // make sure the requested date is not in the future
        Date today = null;
        Calendar todayCal = Calendar.getInstance();
        todayCal = Calendar.getInstance(tz, locale);
        todayCal.setTime(new Date());
        today = todayCal.getTime();
        if (ret.after(today)) {
            ret = today;
        }

    } else if (dateString != null && dateString.length() == 6 && StringUtils.isNumeric(dateString)) {
        ParsePosition pos = new ParsePosition(0);
        ret = char6DateFormat.parse(dateString, pos);

        // make sure the requested date is not in the future
        Calendar todayCal = Calendar.getInstance();
        todayCal = Calendar.getInstance(tz, locale);
        todayCal.setTime(new Date());
        Date today = todayCal.getTime();
        if (ret.after(today)) {
            ret = today;
        }
    }

    return ret;
}

From source file:org.noorganization.instalistsynch.controller.local.dba.impl.SqliteGroupAccessDbControllerTest.java

License:asdf

public void testUpdate() throws Exception {
    Date currentDate = new Date();
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(GroupAccess.COLUMN.GROUP_ID, 1);
    cv.put(GroupAccess.COLUMN.INTERRUPTED, false);
    cv.put(GroupAccess.COLUMN.SYNCHRONIZE, true);
    cv.put(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.LAST_TOKEN_REQUEST, ISO8601Utils.format(currentDate));
    cv.put(GroupAccess.COLUMN.TOKEN, "fdskhbvvkddscddueFSNDFSAdnandk3229df-dFSJDKMds.");

    assertTrue(db.insert(GroupAccess.TABLE_NAME, null, cv) >= 0);

    GroupAccess groupAccess = new GroupAccess(1, "fdskhbvvkddscddueasdfeSAdnandk3229df-dFSJDKMds.");
    groupAccess.setLastTokenRequest(currentDate);
    groupAccess.setLastUpdateFromServer(currentDate);
    groupAccess.setSynchronize(true);//from ww  w  .j  av a 2  s  .co m
    groupAccess.setInterrupted(true);

    assertTrue(mGroupAuthAccessDbController.update(groupAccess));

    Cursor cursor = db.query(GroupAccess.TABLE_NAME, GroupAccess.COLUMN.ALL_COLUMNS,
            GroupAccess.COLUMN.GROUP_ID + " = ? ", new String[] { String.valueOf(1) }, null, null, null);
    int count = cursor.getCount();
    if (count == 0)
        cursor.close();

    assertTrue(cursor.moveToFirst());
    int groupId = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.GROUP_ID));
    boolean synchronize = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.SYNCHRONIZE)) == 1;
    boolean interrupted = cursor.getInt(cursor.getColumnIndex(GroupAccess.COLUMN.INTERRUPTED)) == 1;
    Date lastTokenRequestDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_TOKEN_REQUEST)),
            new ParsePosition(0));
    Date lastUpdateDate = ISO8601Utils.parse(
            cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.LAST_UPDATE_FROM_SERVER)),
            new ParsePosition(0));
    String token = cursor.getString(cursor.getColumnIndex(GroupAccess.COLUMN.TOKEN));
    cursor.close();

    assertEquals(1, groupId);
    assertEquals(true, synchronize);
    assertEquals(true, interrupted);
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastTokenRequestDate));
    assertEquals(ISO8601Utils.format(currentDate), ISO8601Utils.format(lastUpdateDate));

    assertEquals("fdskhbvvkddscddueasdfeSAdnandk3229df-dFSJDKMds.", token);

}

From source file:org.talend.core.model.metadata.builder.database.dburl.SupportDBUrlStore.java

public Properties getDBPameterProperties(String connectionStr) {
    Properties paramProperties = new Properties();
    if (connectionStr != null) {
        String matchSubStr = connectionStr.substring(0, 8);
        Set<Object> s = PROP.keySet();
        Iterator<Object> it = s.iterator();
        while (it.hasNext()) {
            String id = (String) it.next();
            String value = PROP.getProperty(id);
            if (value.contains(matchSubStr)) {
                paramProperties.setProperty(PluginConstant.DBTYPE_PROPERTY, id);
                MessageFormat mf = new MessageFormat(value);
                Object[] parseResult = mf.parse(connectionStr, new ParsePosition(0));
                if (parseResult != null) {
                    if (parseResult[0] != null) {
                        paramProperties.setProperty(PluginConstant.HOSTNAME_PROPERTY, (String) parseResult[0]);
                    }//from w w  w.j a  v a2 s  . co  m

                    if (parseResult[1] != null) {
                        paramProperties.setProperty(PluginConstant.PORT_PROPERTY, (String) parseResult[1]);
                    }

                    break;
                }
            }
        }
    } else {
        paramProperties.setProperty(PluginConstant.DBTYPE_PROPERTY, "");
        paramProperties.setProperty(PluginConstant.HOSTNAME_PROPERTY, "");
        paramProperties.setProperty(PluginConstant.PORT_PROPERTY, "");
    }

    return paramProperties;
}

From source file:us.mn.state.health.lims.common.util.DateUtil.java

public static synchronized int decodeTime(String s) throws Exception {
    SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
    // System.out.println("Passed in this time " +s);
    TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
    f.setTimeZone(utcTimeZone);/* w w w . j  av  a2s.com*/
    f.setLenient(false);
    ParsePosition p = new ParsePosition(0);
    Date d = f.parse(s, p);
    if (d == null || !StringUtil.isRestOfStringBlank(s, p.getIndex())) {
        throw new Exception("Invalid time value (hh:mm:ss): \"" + s + "\".");
    }
    return (int) d.getTime();
}