List of usage examples for java.sql Timestamp getTime
public long getTime()
From source file:com.tesora.dve.sql.CurrentTimestampDefaultValueTest.java
@Test public void testSimpleQueriesForTimestampVariable() throws Throwable { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH); int i = 0;// ww w . j a v a 2s . co m for (Object[] objects : TimestampVariableTestUtils.getTestValues()) { String value = (String) objects[0]; Boolean nullable = BooleanUtils.toBoolean((Integer) objects[1]); String defaultValue = (String) objects[2]; Boolean onUpdate = BooleanUtils.toBoolean((Integer) objects[3]); Boolean expectedInsertTSVarSet = BooleanUtils.toBoolean((Integer) objects[4]); Boolean expectedUpdateTSVarSet = BooleanUtils.toBoolean((Integer) objects[5]); Boolean ignoreTest = BooleanUtils.toBoolean((Integer) objects[6]); if (ignoreTest) { continue; } String tableName = "ts" + i; String createTableSQL = TimestampVariableTestUtils.buildCreateTableSQL(tableName, nullable, defaultValue, onUpdate); String insertSQL = TimestampVariableTestUtils.buildInsertTestSQL(tableName, value, 1, Integer.toString(i)); String updateSQL = TimestampVariableTestUtils.buildUpdateTestSQL(tableName, value, 1, Integer.toString(i) + Integer.toString(i)); ++i; conn.execute(createTableSQL); long preTestTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); conn.execute(insertSQL); ResourceResponse resp = conn.fetch("select ts from " + tableName + " where id=1"); List<ResultRow> rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); ResultColumn rc = rows.get(0).getResultColumn(1); if (expectedInsertTSVarSet) { // if we expected to set the timestamp variable then the ts column must contain the current time Timestamp ts = (Timestamp) (rc.getColumnValue()); assertTrue("Inserted time must be >= starting time", preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime())); } else { boolean isNull = rc.isNull(); if (!isNull) { // ts column is not null so let's see if the column value was specified and if it was it should match the ts value Timestamp ts = (Timestamp) (rc.getColumnValue()); if (StringUtils.contains(value, "2000-01-01 01:02:03")) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime())); } else if (StringUtils.equals("0", value)) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime())); } else if (StringUtils.equals("current_timestamp", value)) { assertTrue("Inserted time must be >= starting time", preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime())); } else { // if we get here column value is not specified so figure out what default value we need if (StringUtils.contains(defaultValue, "2000-01-01 01:02:03")) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime())); } else if (StringUtils.equals("0", defaultValue)) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime())); } else if (StringUtils.equals("current_timestamp", defaultValue)) { assertTrue("Inserted time must be >= starting time", preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime())); } } } else { // column better be nullable assertTrue(nullable); if (StringUtils.isBlank(value)) { // column not specified better validate the default value assertTrue(StringUtils.equals("null", defaultValue) || StringUtils.isBlank(defaultValue)); } else { // column value was specified as null assertEquals("null", value); } } } long updatePreTestTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); conn.execute(updateSQL); resp = conn.fetch("select ts from " + tableName + " where id=1"); rows = resp.getResults(); assertEquals("Expected one row only", 1, rows.size()); rc = rows.get(0).getResultColumn(1); if (expectedUpdateTSVarSet) { // if we expected to set the timestamp variable then the ts column must contain the current time Timestamp ts = (Timestamp) (rc.getColumnValue()); assertTrue("Update time must be >= starting time", updatePreTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime())); } else { boolean isNull = rc.isNull(); if (!isNull) { // ts column is not null so let's see if the column value was specified and if it was it should match the ts value Timestamp ts = (Timestamp) (rc.getColumnValue()); if (StringUtils.contains(value, "2000-01-01 01:02:03")) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime())); } else if (StringUtils.equals("0", value)) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime())); } else if (StringUtils.equals("current_timestamp", value)) { assertTrue("Inserted time must be >= starting time", preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime())); } else { // if we get here column value is not specified so figure out what default value we need if (StringUtils.contains(defaultValue, "2000-01-01 01:02:03")) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime())); } else if (StringUtils.equals("0", defaultValue)) { assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime())); } else if (StringUtils.equals("current_timestamp", defaultValue)) { assertTrue("Inserted time must be >= starting time", preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime())); } } } else { // column better be nullable assertTrue(nullable); if (StringUtils.isBlank(value)) { // column not specified better validate the default value // note in one case the default is not specified and no value was specified for the column // then the column value is null so the blank default is ok assertTrue(StringUtils.equals("null", defaultValue) || StringUtils.isBlank(defaultValue)); } else { // column value was specified as null assertEquals("null", value); } } } } }
From source file:org.eevolution.form.CRP.java
/** * Create Category Dataset based on Weight , date start and resource * @param start/*from w w w. ja v a 2s . c o m*/ * @param resource * @return CategoryDataset */ protected CategoryDataset createWeightDataset(Timestamp start, MResource rosource) { GregorianCalendar gc1 = new GregorianCalendar(); gc1.setTimeInMillis(start.getTime()); gc1.clear(Calendar.MILLISECOND); gc1.clear(Calendar.SECOND); gc1.clear(Calendar.MINUTE); gc1.clear(Calendar.HOUR_OF_DAY); String namecapacity = Msg.translate(Env.getCtx(), "Capacity"); String nameload = Msg.translate(Env.getCtx(), "Load"); String namesummary = Msg.translate(Env.getCtx(), "Summary"); String namepossiblecapacity = "Possible Capacity"; MResourceType t = MResourceType.get(Env.getCtx(), rosource.getS_ResourceType_ID()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); double currentweight = DB.getSQLValue(null, "SELECT SUM( (mo.qtyordered-mo.qtydelivered)*(SELECT mp.weight FROM M_Product mp WHERE mo.m_product_id=mp.m_product_id )) FROM PP_Order mo WHERE AD_Client_ID=?", rosource.getAD_Client_ID()); double dailyCapacity = rosource.getDailyCapacity().doubleValue(); double utilization = rosource.getPercentUtilization().doubleValue(); double summary = 0; int day = 0; while (day < 32) { day++; switch (gc1.get(Calendar.DAY_OF_WEEK)) { case Calendar.SUNDAY: if (t.isOnSunday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; case Calendar.MONDAY: if (t.isOnMonday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; case Calendar.TUESDAY: if (t.isOnTuesday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; case Calendar.WEDNESDAY: if (t.isOnWednesday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; case Calendar.THURSDAY: if (t.isOnThursday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; case Calendar.FRIDAY: if (t.isOnFriday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; case Calendar.SATURDAY: if (t.isOnSaturday()) { currentweight -= (dailyCapacity * utilization) / 100; summary += ((dailyCapacity * utilization) / 100); dataset.addValue(dailyCapacity, namepossiblecapacity, new Integer(day)); dataset.addValue((dailyCapacity * utilization) / 100, namecapacity, new Integer(day)); } else { dataset.addValue(0, namepossiblecapacity, new Integer(day)); dataset.addValue(0, namecapacity, new Integer(day)); } break; } dataset.addValue(currentweight, nameload, new Integer(day)); dataset.addValue(summary, namesummary, new Integer(day)); gc1.add(Calendar.DATE, 1); } return dataset; }
From source file:abelymiguel.miralaprima.GetPrima.java
private Boolean isUpdatedDMacro(String country) { Boolean isUpdated = false;/*from w w w .ja v a 2 s .c o m*/ try { Timestamp date_today = this.getTimestamp(); Timestamp dateLastUpdate = this.getDateOfLastStored(country); if (dateLastUpdate != null) { if (dateLastUpdate.getTime() > date_today.getTime() - 1800000) { isUpdated = true; } } } catch (Exception e) { Logger.getLogger(GetPrima.class.getName()).log(Level.WARNING, null, e); isUpdated = true; } return isUpdated; }
From source file:abelymiguel.miralaprima.GetPrima.java
private Boolean isUpdatedBloom(String country) { Boolean isUpdated = false;//from ww w . ja v a2 s . c o m try { Timestamp date_today = this.getTimestamp(); Timestamp dateLastUpdate = this.getDateOfLastStored(country); if (dateLastUpdate != null) { if (dateLastUpdate.getTime() > date_today.getTime() - 500000) { isUpdated = true; } } } catch (Exception e) { Logger.getLogger(GetPrima.class.getName()).log(Level.WARNING, null, e); isUpdated = true; } return isUpdated; }
From source file:org.azkfw.datasource.xml.XmlDatasourceBuilder.java
private XmlRecord readData(final int aRowNum, final XmlRecordEntity aRecord, final List<XmlField> aFields) throws ParseException { Map<String, Object> data = new HashMap<String, Object>(); for (int i = 0; i < aFields.size(); i++) { XmlField field = aFields.get(i); XmlRecordDataEntity d = aRecord.data.get(i); String value = d.value;/*from www .j av a2 s. c o m*/ if (nullString.equals(value)) { data.put(field.name, null); } else { if (FieldType.String == field.type) { String obj = value; data.put(field.name, obj); } else if (FieldType.Boolean == field.type) { Boolean obj = Boolean.parseBoolean(value); data.put(field.name, obj); } else if (FieldType.Integer == field.type) { Double obj = Double.parseDouble(value); data.put(field.name, Integer.valueOf(obj.intValue())); } else if (FieldType.Long == field.type) { Double obj = Double.parseDouble(value); data.put(field.name, Long.valueOf(obj.longValue())); } else if (FieldType.Float == field.type) { Float obj = Float.parseFloat(value); data.put(field.name, obj); } else if (FieldType.Double == field.type) { Double obj = Double.parseDouble(value); data.put(field.name, obj); } else if (FieldType.Timestamp == field.type) { Timestamp obj = new Timestamp( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(value).getTime()); data.put(field.name, obj); } else if (FieldType.Date == field.type) { Timestamp ts = new Timestamp(new SimpleDateFormat("yyyy/MM/dd").parse(value).getTime()); Date obj = new Date(ts.getTime()); data.put(field.name, obj); } else if (FieldType.Time == field.type) { Timestamp ts = new Timestamp(new SimpleDateFormat("HH:mm:ss").parse(value).getTime()); Time obj = new Time(ts.getTime()); data.put(field.name, obj); } else { throw new ParseException("Undefined type.[" + field.getType() + "]", aRowNum); } } } XmlRecord record = new XmlRecord(); record.data = data; return record; }
From source file:org.projectforge.task.TaskDao.java
/** * Gets the total duration of all time sheets of all tasks (excluding the child tasks). * @param node//from w ww . ja v a2 s . co m * @return */ @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public List<Object[]> readTotalDurations() { log.debug("Calculating duration for all tasks"); final String intervalInSeconds = DatabaseSupport.instance().getIntervalInSeconds("startTime", "stopTime"); if (intervalInSeconds != null) { @SuppressWarnings("unchecked") final List<Object[]> list = getHibernateTemplate().find("select " + intervalInSeconds + ", task.id from TimesheetDO where deleted=false group by task.id"); return list; } @SuppressWarnings("unchecked") final List<Object[]> result = getHibernateTemplate() .find("select startTime, stopTime, task.id from TimesheetDO where deleted=false order by task.id"); final List<Object[]> list = new ArrayList<Object[]>(); if (CollectionUtils.isEmpty(result) == false) { Integer currentTaskId = null; long totalDuration = 0; for (final Object[] oa : result) { final Timestamp startTime = (Timestamp) oa[0]; final Timestamp stopTime = (Timestamp) oa[1]; final Integer taskId = (Integer) oa[2]; final long duration = (stopTime.getTime() - startTime.getTime()) / 1000; if (currentTaskId == null || currentTaskId.equals(taskId) == false) { if (currentTaskId != null) { list.add(new Object[] { totalDuration, currentTaskId }); } // New row. currentTaskId = taskId; totalDuration = 0; } totalDuration += duration; } if (currentTaskId != null) { list.add(new Object[] { totalDuration, currentTaskId }); } } return list; }
From source file:org.kuali.kfs.module.tem.document.TEMReimbursementDocument.java
/** * Just returns the date back//from w ww . j ava2 s . c o m * @see org.kuali.kfs.module.tem.document.TravelDocument#getEffectiveDateForPerDiem(java.sql.Date) */ @Override public Date getEffectiveDateForPerDiem(java.sql.Timestamp expenseDate) { return new java.sql.Date(expenseDate.getTime()); }
From source file:org.eevolution.form.CRP.java
/** * Create Category Dataset based on date start and resource * @param start/*from w ww.ja va 2 s . co m*/ * @param resource * @return CategoryDataset */ protected CategoryDataset createDataset(Timestamp start, MResource resource) { GregorianCalendar gc1 = new GregorianCalendar(); gc1.setTimeInMillis(start.getTime()); gc1.clear(Calendar.MILLISECOND); gc1.clear(Calendar.SECOND); gc1.clear(Calendar.MINUTE); gc1.clear(Calendar.HOUR_OF_DAY); Timestamp date = start; String namecapacity = Msg.translate(Env.getCtx(), "Capacity"); String nameload = Msg.translate(Env.getCtx(), "Load"); String namesummary = Msg.translate(Env.getCtx(), "Summary"); MResourceType t = MResourceType.get(Env.getCtx(), resource.getS_ResourceType_ID()); int days = 1; long hours = t.getTimeSlotHours(); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); // Long Hours = new Long(hours); int C_UOM_ID = DB.getSQLValue(null, "SELECT C_UOM_ID FROM M_Product WHERE S_Resource_ID = ? ", resource.getS_Resource_ID()); MUOM uom = MUOM.get(Env.getCtx(), C_UOM_ID); if (!uom.isHour()) { return dataset; } long summary = 0; while (days < 32) { String day = new String(new Integer(date.getDate()).toString()); long HoursLoad = getLoad(resource, date).longValue(); Long Hours = new Long(hours); switch (gc1.get(Calendar.DAY_OF_WEEK)) { case Calendar.SUNDAY: days++; if (t.isOnSunday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } case Calendar.MONDAY: days++; if (t.isOnMonday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } case Calendar.TUESDAY: days++; if (t.isOnTuesday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } case Calendar.WEDNESDAY: days++; if (t.isOnWednesday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } case Calendar.THURSDAY: days++; if (t.isOnThursday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } case Calendar.FRIDAY: days++; if (t.isOnFriday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } case Calendar.SATURDAY: days++; if (t.isOnSaturday()) { dataset.addValue(hours, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary + Hours.intValue() - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } else { dataset.addValue(0, namecapacity, day); dataset.addValue(HoursLoad, nameload, day); dataset.addValue(summary, namesummary, day); summary = summary - (HoursLoad); gc1.add(Calendar.DATE, 1); date = new Timestamp(gc1.getTimeInMillis()); break; } } } return dataset; }
From source file:com.examples.with.different.packagename.testcarver.DateTimeConverter.java
/** * Convert the input object into a Date object of the * specified type.//from w ww . j ava2 s .c o m * <p> * This method handles conversions between the following * types: * <ul> * <li><code>java.util.Date</code></li> * <li><code>java.util.Calendar</code></li> * <li><code>java.sql.Date</code></li> * <li><code>java.sql.Time</code></li> * <li><code>java.sql.Timestamp</code></li> * </ul> * * It also handles conversion from a <code>String</code> to * any of the above types. * <p> * * For <code>String</code> conversion, if the converter has been configured * with one or more patterns (using <code>setPatterns()</code>), then * the conversion is attempted with each of the specified patterns. * Otherwise the default <code>DateFormat</code> for the default locale * (and <i>style</i> if configured) will be used. * * @param targetType Data type to which this value should be converted. * @param value The input value to be converted. * @return The converted value. * @throws Exception if conversion cannot be performed successfully */ protected Object convertToType(Class targetType, Object value) throws Exception { Class sourceType = value.getClass(); // Handle java.sql.Timestamp if (value instanceof java.sql.Timestamp) { // ---------------------- JDK 1.3 Fix ---------------------- // N.B. Prior to JDK 1.4 the Timestamp's getTime() method // didn't include the milliseconds. The following code // ensures it works consistently accross JDK versions java.sql.Timestamp timestamp = (java.sql.Timestamp) value; long timeInMillis = ((timestamp.getTime() / 1000) * 1000); timeInMillis += timestamp.getNanos() / 1000000; // ---------------------- JDK 1.3 Fix ---------------------- return toDate(targetType, timeInMillis); } // Handle Date (includes java.sql.Date & java.sql.Time) if (value instanceof Date) { Date date = (Date) value; return toDate(targetType, date.getTime()); } // Handle Calendar if (value instanceof Calendar) { Calendar calendar = (Calendar) value; return toDate(targetType, calendar.getTime().getTime()); } // Handle Long if (value instanceof Long) { Long longObj = (Long) value; return toDate(targetType, longObj.longValue()); } // Convert all other types to String & handle String stringValue = value.toString().trim(); if (stringValue.length() == 0) { return handleMissing(targetType); } // Parse the Date/Time if (useLocaleFormat) { Calendar calendar = null; if (patterns != null && patterns.length > 0) { calendar = parse(sourceType, targetType, stringValue); } else { DateFormat format = getFormat(locale, timeZone); calendar = parse(sourceType, targetType, stringValue, format); } if (Calendar.class.isAssignableFrom(targetType)) { return calendar; } else { return toDate(targetType, calendar.getTime().getTime()); } } // Default String conversion return toDate(targetType, stringValue); }
From source file:org.traccar.database.QueryBuilder.java
private <T> void addProcessors(List<ResultSetProcessor<T>> processors, final Class<?> parameterType, final Method method, final String name) { if (parameterType.equals(boolean.class)) { processors.add(new ResultSetProcessor<T>() { @Override/* ww w . j a v a 2s .c om*/ public void process(T object, ResultSet resultSet) throws SQLException { try { method.invoke(object, resultSet.getBoolean(name)); } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else if (parameterType.equals(int.class)) { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { try { method.invoke(object, resultSet.getInt(name)); } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else if (parameterType.equals(long.class)) { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { try { method.invoke(object, resultSet.getLong(name)); } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else if (parameterType.equals(double.class)) { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { try { method.invoke(object, resultSet.getDouble(name)); } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else if (parameterType.equals(String.class)) { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { try { method.invoke(object, resultSet.getString(name)); } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else if (parameterType.equals(Date.class)) { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { try { Timestamp timestamp = resultSet.getTimestamp(name); if (timestamp != null) { method.invoke(object, new Date(timestamp.getTime())); } } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else if (parameterType.equals(byte[].class)) { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { try { method.invoke(object, resultSet.getBytes(name)); } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } }); } else { processors.add(new ResultSetProcessor<T>() { @Override public void process(T object, ResultSet resultSet) throws SQLException { String value = resultSet.getString(name); if (value != null && !value.isEmpty()) { try { method.invoke(object, Context.getObjectMapper().readValue(value, parameterType)); } catch (InvocationTargetException | IllegalAccessException | IOException error) { Log.warning(error); } } } }); } }